我已经看到两个不同的Python对象用于将任意数据组合在一起:空类和函数.
def struct():
pass
record = struct
record.number = 3
record.name = "Zoe"
class Struct:
pass
record = Struct()
record.number = 3
record.name = "Zoe"
Run Code Online (Sandbox Code Playgroud)
即使该类不为空,只要它在运行时定义,它似乎也可以工作.
但是当我自大并试图用内置函数或类来做这件事时,它没有用.
record = set()
record.number = 3
AttributeError: 'set' object has no attribute 'number'
record = pow
pow.number = 3
AttributeError: 'builtin_function_or_method' object has no attribute 'number'
Run Code Online (Sandbox Code Playgroud)
内置和"自定义"类和函数之间是否存在根本区别?
区别在于函数对象和Struct对象都有一个__dict__属性,但set实例和内置函数不具有:
>>> def struct():
... pass
...
>>> record = struct
>>> record.number = 2
>>> struct.__dict__
{'number': 2}
>>> class Struct:
... pass
...
>>> record = Struct()
>>> record.number = 3
>>> record.__dict__
{'number': 3}
>>> record=set()
>>> record.__dict__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'set' object has no attribute '__dict__'
>>> pow.__dict__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute '__dict__'
Run Code Online (Sandbox Code Playgroud)
您可以使用插槽来模拟行为(尽管只在新式类上):
>>> class StructWithSlots(object):
... __slots__ = []
...
>>> record = StructWithSlots()
>>> record.number = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'StructWithSlots' object has no attribute 'number'
>>> record.__dict__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'StructWithSlots' object has no attribute '__dict__'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1369 次 |
| 最近记录: |