考虑这个例子:
>>> class Bar(object):
...
... def __init__(self, name):
... self.name = name
... def __set__(self, instance, value):
... setattr(instance, self.name, value)
... def __get__(self, instance, owner):
... return getattr(instance, self.name, owner)
...
>>> class Foo(object):
... bat = Bar('bat')
...
>>> Foo.bat
<class 'Foo'>
>>> type(Foo.bat)
<class 'type'> # how would you get <class 'Bar'> ?
我想写一些pytests
断言正确的描述符已分配给正确的属性。
但是,一旦分配了描述符,我似乎无法检查它的类型
答案 0 :(得分:2)
您可以使用type
覆盖通常的查找(使用您尝试查看的描述符,无论您是否在结果上调用vars(Foo)['bat']
。)
答案 1 :(得分:2)
我不确定你要对你的描述符做什么,但通常你想在未传递实例时传回描述符本身:
class Bar(object):
def __init__(self, name):
self.name = name
def __set__(self, obj, value):
setattr(obj, self.name, value)
def __get__(self, obj, cls):
if obj is None:
return self
return getattr(obj, self.name)
class Foo(object):
bat = Bar('bat')
Foo.bat
# <__main__.Bar at 0x7f202accbf50>