我尝试使用数据描述符为类的属性提供自定义的get/set功能。我希望能够在运行时检查类并获取该类上的数据描述符列表,甚至可能确定描述符的类型。
问题在于,当我使用
我正在使用来自http://docs.python.org/2/howto/descriptor.html的示例。
当我运行此代码时,会出现以下信息:
问题在于,当我使用
inspect.getmembers
获取成员时,我的数据描述符属性被解析了(它们的__get__
方法已经被调用,并且该结果被设置为对象的值)。我正在使用来自http://docs.python.org/2/howto/descriptor.html的示例。
import inspect
class RevealAccess(object):
"""A data descriptor that sets and returns values
normally and prints a message logging their access.
"""
def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name
def __get__(self, obj, objtype):
print 'Retrieving', self.name
return self.val
def __set__(self, obj, val):
print 'Updating', self.name
self.val = val
class MyClass(object):
x = RevealAccess(10, 'var "x"')
y = 5
if __name__ == '__main__':
for x in inspect.getmembers(MyClass, inspect.isdatadescriptor):
print x
当我运行此代码时,会出现以下信息:
Retrieving var "x"
('__weakref__', <attribute '__weakref__' of 'MyClass' objects>)
What I expect is more like:
('x', <attribute 'x' of 'MyClass' objects>)
('__weakref__', <attribute '__weakref__' of 'MyClass' objects>)
我知道我缺少什么,但就是想不起来。非常感谢您的帮助。