如何获取Python类属性(而不是实例)的字典?

时间:2019-04-08 15:06:37

标签: python dictionary

我想访问一个类中的属性,以便可以动态更改它们。

我在此站点上看到的答案表明,班级的__dict__将提供此功能,就像我尝试使用以下代码一样:

class Item:
    def __init__(self):
        self.name = ''
        self.description = ''
        self.weight = ''
        self.volume = ''

print(Item.__dict__)

{'__module__': '__main__', '__init__': <function Item.__init__ at 0x0000026F3F5988C8>, '__dict__': <attribute '__dict__' of 'Item' objects>, '__weakref__': <attribute '__weakref__' of 'Item' objects>, '__doc__': None}

似乎我想访问Item.__dict__.['__dict__'],但我不知道该怎么做。

2 个答案:

答案 0 :(得分:1)

正如其他人指出的那样,为了查看实例属性(而不是类属性),您必须实例化该类型的对象。但是,与其使用__dict__属性,不如使用内置的vars函数。

item = Item()
items_attrs = vars(item)

这实际上是做同样的事情,但是看起来有点像Pythonic。


您还可以在类上定义__slots__属性。这将以可能不需要的方式更改类(及其对象)的行为,但使您可以轻松访问感兴趣的信息。值得注意的是,此行为会更改:

  

如果没有__dict__变量,则无法为实例分配__slots__定义中未列出的新变量。尝试分配给未列出的变量名会引发AttributeError。如果需要动态分配新变量,请在'__dict__'声明的字符串序列中添加__slots__

class Item(object):
    __slots__ = ['name',
        'description',
        'weight',
        'volume']

    def __init__(self):
        self.name = ''
        self.description = ''
        self.weight = ''
        self.volume = ''

Item_attrs = Item.__slots__
item = Item()
item_attrs = item.__slots__

assert item_attrs == Item_attrs

答案 1 :(得分:0)

您可能在类变量和实例变量之间感到困惑。在代码的以下修改中,classvar是一个类变量:

class Item:
    classvar = 'foo'

    def __init__(self):
        self.name = ''
        self.description = ''
        self.weight = ''
        self.volume = ''

现在Item.__dict__将包含classvar。但是实例类只有在实例化该类之后才创建:

i1 = Item()
print(i1.__dict__())  # will contain 'name', 'description' etc.

但是,为什么要和__dict__一起玩呢?只有某些代码自省技巧才需要它。您可以仅通过点符号来访问类和实例变量:

print(Item.classvar)
i1 = Item()
print(i1.name)