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

2024-05-11 12:40:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下课程:

class TestClass(object):
def __init__(self, **kwargs):
    for key, value in kwargs.items(): #items return list of dict
        setattr(self, key, value)

示例用途:

^{pr2}$

如何在不知道属性名称的情况下迭代这个结构?Python为我们提供了内置方法__getattribute__,但我仍然需要知道所请求属性的名称:

print(obj.__getattribute__("testkey1"))

Tags: keyself名称for属性objectinitvalue
1条回答
网友
1楼 · 发布于 2024-05-11 12:40:53

__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})

任何实例都有:

^{pr2}$

您应该通过vars内置函数访问此属性。 调用vars(foo)将返回foo.__dict__。 请参阅相关帖子:Use ^{} or ^{}?。在

Documentation for ^{}

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要干净得多,因为您自己定义了要访问的内容。 它能让你更好地控制班级的行为。在

相关问题 更多 >