gpt4 book ai didi

python - 获取类属性的属性名

转载 作者:太空宇宙 更新时间:2023-11-03 13:08:24 35 4
gpt4 key购买 nike

这里有两个离散的对象:

class Field(object):
pass

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

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

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

谢谢!

最佳答案

是的,您可以将 Field 类设为 descriptor , 然后使用 __set_name__绑定(bind)名称的方法。 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'

关于python - 获取类属性的属性名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50477066/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com