是的,您可以将Field
类设为描述符,然后使用__set_name__
方法绑定名称。中不需要特殊处理MyClass
。
object.__set_name__(self, owner, 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'