python - 如何在不知道类名的情况下获取类的属性

标签 python

我有以下类(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()? .

Documentation for 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 a types.MappingProxyType to prevent direct dictionary updates).

Without an argument, vars() acts like locals(). 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/

相关文章:

python - Teamcity pytest 插件和单元测试报告

python - 我如何计算这张图片中的颗粒数

python - 如何更改 numpy 数组的一部分的值?

python - Argparse - 没有参数的自定义操作?

c++ - C++ 的 Python 风格 pickle ?

python - 为什么 'is' 运算符在算术相等表达式中表现异常

python - 在文件路径中测试 '/../' 是否足以防止转义子目录?

Python:不同的空集列表

python - Pandas 中的不规则、不连续的周期

python - 从 webscrape 输出中删除 'u