3

这是两个离散对象:

class Field(object):
    pass

class MyClass(object):
    firstname = Field()
    lastname = Field()
    email = Field()

对于任何Field对象,是否有一种方法可以让该对象知道MyClass分配给它的属性名称?

我知道我可以将参数传递给Field对象,例如email = Field(name='email'),但在我的实际情况下这会很混乱和乏味,所以我只是想知道是否有一种非手动的方式来做同样的事情。

谢谢!

4

1 回答 1

8

是的,您可以将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'
于 2018-05-22T22:10:10.383 回答