Skip to content Skip to sidebar Skip to footer

Python Decorator Also For Undefined Attributes

I'd like to create a Model Class for an User. The data of the user are stored in an document based database like couchdb or mongodb. The class User should have an decorator and the

Solution 1:

You need to implement the __getattr__(self, name)method.

Solution 2:

Access to an object's attributes is governed by the getattr/setattr/delattr/getattribute mechanism.

Solution 3:

Django uses metaclasses to dynamically create models. While your requirements are a little different, the same technique will work (probably better then decorators).

You can read more about Python metaclasses on Stackoverflow.

Solution 4:

I think i found a solution based on your suggestions:

defDocumentDB(object):
    classTransparentAttribute:
        def__init__(self, *args, **kargs):                 
            self.wrapped = object(*args, **kargs)
        def__getattr__(self, attrname):
            return"Any Value"return TransparentAttribute

@DocumentDBclassUser(object):
    defdoSomething(self):
        passdefdoSomethingElse(self):
        pass

u = User()
print u.emailAddress
print u.lastName

It works, but is it the most pythoniastic way?

Post a Comment for "Python Decorator Also For Undefined Attributes"