gpt4 book ai didi

python - 在 python 中检查数据描述符属性

转载 作者:太空宇宙 更新时间:2023-11-03 11:06:41 26 4
gpt4 key购买 nike

我正在尝试使用数据描述符为类的属性提供一些自定义的获取/设置功能。我希望能够在运行时检查类并获取该类的数据描述符列表,甚至可能确定描述符的类型。

问题是,当我查看成员时,我使用 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>)

期望更像是:

('x', <attribute 'x' of 'MyClass' objects>)
('__weakref__', <attribute '__weakref__' of 'MyClass' objects>)

我知道我遗漏了一些我无法确定的东西。任何帮助表示赞赏。

最佳答案

要获取描述符本身,您可以查看类 __dict__:

MyClass.__dict__['x']

但更好的方法是修改getter:

def __get__(self, obj, objtype):
print 'Retrieving', self.name
if obj is None: # accessed as class attribute
return self # return the descriptor itself
else: # accessed as instance attribute
return self.val # return a value

给出:

Retrieving var "x"
('__weakref__', <attribute '__weakref__' of 'MyClass' objects>)
('x', <__main__.RevealAccess object at 0x7f32ef989890>)

关于python - 在 python 中检查数据描述符属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17368930/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com