【问题标题】:Python: why is __dict__ attribute not in built-in class instancesPython:为什么 __dict__ 属性不在内置类实例中
【发布时间】:2012-02-29 15:46:28
【问题描述】:

如果我对 Python 数据模型的理解是正确的,那么类和类实例都关联了包含所有属性的 __dict__ 对象。但是,我有点困惑为什么某些类实例(例如 str 的实例)没有 __dict__ 属性。

如果我创建一个自定义类:

class Foo:
     def __init__(self):
             self.firstname = "John"
             self.lastname = "Smith"

然后我可以通过说得到实例变量:

>>> f = Foo()
>>> print(f.__dict__)
{'lastname': 'Smith', 'firstname': 'John'}

但如果我尝试对内置 str 的实例做同样的事情,我会得到:

>>> s = "abc"
>>> print(s.__dict__)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute '__dict__'

那么,为什么str 的实例没有__dict__ 属性?

【问题讨论】:

  • 详细说明一下,如果每个字典都有__dict__,那么也必须有__dict__.__dict__——递归应该走多远?

标签: python


【解决方案1】:

默认情况下,C 中定义的类型实例没有 __dict__ 属性。

【讨论】:

    【解决方案2】:

    只是补充一下:

    您可以使用以下方法获得相当于只读的__dict__:

    {s:getattr(x, s) for s in dir(x)}
    

    编辑:请注意,这可能包含比__dict__ 更多的条目。为了避免这种情况,您可以将其用作解决方法:

    {s:getattr(x, s) for s in dir(x) if not s.startswith("__")}
    

    【讨论】:

    • 应该是{s:getattr(x,s) for s in dir(x)},并且包含不在__dict__中的条目。
    • 谢谢,这是一个很大的改进,现在在许多情况下都可以使用。但是,如果对象包含函数,__dict__ 不会返回这些函数,但{s:getattr(x, s) for s in dir(x) if not s.startswith("__")} 会。示例:class A(): def b(): pass
    • 它还会列出__dict__ 不会列出的类级变量。
    猜你喜欢
    • 2011-06-20
    • 2012-05-20
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 2016-12-01
    • 2013-01-09
    相关资源
    最近更新 更多