Python Decorator also for undefined attributes

不问归期 提交于 2019-12-13 06:30:56

问题


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 fields ind the db are accessible over not really existing class attributes. For example

@DocumentDB()
class User(object):
    def doSomething(self):
        pass
    def doSomethingElse(self):
        pass

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

I've played around with python decorators. Manipulating existing functions is not a big thing but how can i catch the call for not existing getters/setters to create transparent access to db values trough the instance of the object?


回答1:


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




回答2:


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




回答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.




回答4:


I think i found a solution based on your suggestions:

def DocumentDB(object):
    class TransparentAttribute:
        def __init__(self, *args, **kargs):                 
            self.wrapped = object(*args, **kargs)
        def __getattr__(self, attrname):
            return "Any Value"
    return TransparentAttribute

@DocumentDB
class User(object):
    def doSomething(self):
        pass
    def doSomethingElse(self):
        pass

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

It works, but is it the most pythoniastic way?



来源:https://stackoverflow.com/questions/14333553/python-decorator-also-for-undefined-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!