python – 获取类属性的属性名称

这是两个离散的对象:

class Field(object):
    pass

class MyClass(object):
    spam = Field()
    eggs = Field()
    potato = Field()

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

我知道我可以将参数传递给Field对象,比如potato = Field(name =’potato’),但在我的实际案例中这将是混乱和繁琐的,所以我只是想知道是否有一种非手动的方式来做一样.

谢谢!

最佳答案 是的,您可以将Field类设为
descriptor,然后使用
__set_name__方法绑定名称. MyClass不需要特殊处理.

object.__set_name__(self, owner, name)
Called at the time the owning class owner is created. The descriptor has been assigned to name.

该方法是available in 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'
点赞