cam*_*mil 4 python attributes object
为什么会引发错误:
o = object()
o.i = 1
Run Code Online (Sandbox Code Playgroud)
但这不是:
class A(object):
pass
a = A()
a.i = 1
Run Code Online (Sandbox Code Playgroud)
?
因为内置类型没有与它们关联的字典来保存添加的属性:
>>> o = object()
>>> dir(o)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
Run Code Online (Sandbox Code Playgroud)
看到?不__dict__.
但是添加一个子类会将属性放在某个地方:
>>> class A(object):
.... pass
....
>>> a = A()
>>> dir(a)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
Run Code Online (Sandbox Code Playgroud)
说它是"因为它们在C中定义"并不是"为什么".您当然可以使用实例字典在C中定义类型.
| 归档时间: |
|
| 查看次数: |
103 次 |
| 最近记录: |