获取类属性的属性名称

时间:2018-05-22 22:01:40

标签: python python-3.5 python-descriptors

这是两个不连续的对象:

my_list = [input('enter the start date for file %s: ' % i) for i in list(filenames)]

对于任何class Field(object): pass class MyClass(object): spam = Field() eggs = Field() potato = Field() 对象,是否有一种方法让该对象知道Field分配给它的属性名称?

我知道我可以将参数传递给MyClass对象,比如Field,但在我的实际情况下这会很麻烦和乏味,所以我只是想知道是否有非手动方式做同样的事情。

谢谢!

1 个答案:

答案 0 :(得分:7)

是的,您可以将Field类设为descriptor,然后使用__set_name__方法绑定名称。 MyClass中无需特殊处理。

  

object.__set_name__(self, owner, name)   在创建拥有类所有者时调用。描述符已分配给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'