|
《流畅的python》第十章中定义了一个名为vector的自定义类表示多维向量,它实现了__init__、__eq__、__getitem__、__getattr__等,但没有__setitem__,其中__getattr__是以‘xyzt'来显示前4维向量。类中部分代码如下shortcut_names = 'xyzt'
def __getattr__(self,name):
cls = type(self)
if len(name) == 1:
pos = cls.shortcut_names.find(name)
if 0 <= pos < len(self._components): #self._components为向量
return self._components[pos]
msg = ……
raise AttributeError……
在交互台里
>>> a = vector([1,2,3])
>>>a.x, a.y , a.z
>>>1, 2, 3
但是令a.x=4
>>>a.x = 4
>>>a
>>>vectorarray(1,2,3)
>>>a.x
>>>4
可以看到a并没有被改变,但是a.x变成了4。>>>dir(a)会发现多了个 a.x
问题:
1.这叫什么现象,什么原因?
2.如何避免出现这种情况?
3.跟猴子补丁有何不同?
求大神指点!~
|
|