我有以下类(class):
class TestClass(object):
def __init__(self, **kwargs):
for key, value in kwargs.items(): #items return list of dict
setattr(self, key, value)
示例使用:
obj = MessageItem(**{"testkey1":"tval1", "tkey2":"tval2", "tkey3":"tval3"})
如何在不知道属性名称的情况下迭代此结构? Python 为我们提供了内置方法__getattribute__
,但我仍然需要知道所请求的属性的名称:
print(obj.__getattribute__("testkey1"))
最佳答案
__dict__
属性包含您想要的内容。
类有它:
>>> class Foo:
... def __init__(self, x):
... self.x = x
...
>>> Foo.__dict__
mappingproxy({'__module__': '__main__', '__init__': <function Foo.__init__ at
0x000001CC1821EEA0>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__':
<attribute '__weakref__' of 'Foo' objects>, '__doc__': None})
任何实例都有它:
>>> f = Foo(2)
>>> f.__dict__
{'x': 2}
您应该通过 vars
内置函数访问此属性。
调用 vars(foo)
将返回 foo.__dict__
。
请参阅此相关帖子:Use __dict__
or vars()
? .
vars([object])
Return the
__dict__
attribute for a module, class, instance, or any other object with a__dict__
attribute.Objects such as modules and instances have an updateable
__dict__
attribute; however, other objects may have write restrictions on their__dict__
attributes (for example, classes use atypes.MappingProxyType
to prevent direct dictionary updates).Without an argument,
vars()
acts likelocals()
. Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.
此外,我尝试并编写了一个您可能感兴趣的装饰器。
这是一个类装饰器,它将 initKwargs
添加到它装饰的类中。
此外,它还包装了该类的 __init__
方法,以便将它接收到的 kwargs
字典附加到类的 initKwargs
属性。
def class_wrapper(cls):
cls.initKwargs = []
f = cls.__init__
def wrapped_init(instance, **kwargs):
cls.initKwargs.append(kwargs)
return f(instance, **kwargs)
cls.__init__ = wrapped_init
return cls
@class_wrapper
class Foo:
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
演示:
>>> f1 = Foo()
>>> f2 = Foo(a=1, b=2)
>>> f3 = Foo(a=1, b=2, c=3, d=4)
>>> Foo.initKwargs
[{}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2, 'c': 3, 'd': 4}]
我发现这种方法比使用 vars
更简洁,因为你知道你在访问什么,因为你自己定义了它。
它使您可以更好地控制类(class)的行为。
关于python - 如何在不知道类名的情况下获取类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45918618/