这是两个不连续的对象:
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
,但在我的实际情况下这会很麻烦和乏味,所以我只是想知道是否有非手动方式做同样的事情。
谢谢!
答案 0 :(得分:7)
是的,您可以将Field
类设为descriptor,然后使用__set_name__
方法绑定名称。 MyClass
中无需特殊处理。
object.__set_name__(self, owner, name)
在创建拥有类所有者时调用。描述符已分配给name。
>>> 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'