Iva*_*van 3 python python-3.5 python-descriptors
这是两个离散的对象:
class Field(object):
pass
class MyClass(object):
spam = Field()
eggs = Field()
potato = Field()
Run Code Online (Sandbox Code Playgroud)
对于任何Field对象,是否存在一种方法让该对象知道MyClass分配它的属性名称?
我知道我可以将参数传递给Field对象,potato = Field(name='potato')但是在我的实际情况下这将是混乱和繁琐的,所以我只是想知道是否有非手动方式做同样的事情.
谢谢!
是的,您可以使Field类成为描述符,然后使用__set_name__方法绑定名称.无需特殊处理MyClass.
object.__set_name__(self, owner, name)在创建拥有类所有者时调用.描述符已分配给name.
此方法适用于Python 3.6+.
>>> class Field:
... def __set_name__(self, owner, name):
... print('__set_name__ was called!')
... print(f'self: {self!r}') # this is the Field instance (descriptor)
... print(f'owner: {owner!r}') # this is the owning class (e.g. MyClass)
... print(f'name: {name!r}') # the name the descriptor was bound to
...
>>> class MyClass:
... potato = Field()
...
__set_name__ was called!
self: <__main__.Field object at 0xcafef00d>
owner: <class '__main__.MyClass'>
name: 'potato'
Run Code Online (Sandbox Code Playgroud)