Python: 测试描述符分配正确
Python: test descriptors assigned correctly
考虑这个例子:
>>> 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
断言正确的描述符已分配给正确的属性。
但是我似乎无法在分配描述符后检查它的类型
您可以使用 vars(Foo)['bat']
.
覆盖通常的查找(无论您是否对结果调用 type
,它都使用您要查看的描述符)
我不确定你想用你的描述符做什么,但通常你想在没有传递实例时传回描述符本身:
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>
考虑这个例子:
>>> 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
断言正确的描述符已分配给正确的属性。
但是我似乎无法在分配描述符后检查它的类型
您可以使用 vars(Foo)['bat']
.
type
,它都使用您要查看的描述符)
我不确定你想用你的描述符做什么,但通常你想在没有传递实例时传回描述符本身:
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>