获取 class 属性的属性名称
Get attribute name of class attribute
这里有两个离散对象:
class Field(object):
pass
class MyClass(object):
firstname = Field()
lastname = Field()
email = Field()
对于任何 Field
对象,是否有一种固有的方式让该对象知道 MyClass
分配给它的属性名称?
我知道我可以将参数传递给 Field
对象,例如 email = Field(name='email')
,但在我的实际情况下这会很混乱和乏味,所以我只是想知道是否有非手动的做同样事情的方法。
谢谢!
是的,你可以让Field
class一个descriptor, and then use __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'
这里有两个离散对象:
class Field(object):
pass
class MyClass(object):
firstname = Field()
lastname = Field()
email = Field()
对于任何 Field
对象,是否有一种固有的方式让该对象知道 MyClass
分配给它的属性名称?
我知道我可以将参数传递给 Field
对象,例如 email = Field(name='email')
,但在我的实际情况下这会很混乱和乏味,所以我只是想知道是否有非手动的做同样事情的方法。
谢谢!
是的,你可以让Field
class一个descriptor, and then use __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'