The following methods can be defined to customize the meaning of
attribute access (use of, assignment to, or deletion of x.name
)
for class instances.
可以定义以下方法用于定制类实例属性的访问的含义(用于赋值, 或删除x.name)
self, name) |
self
). name
is the attribute name.
This method should return the (computed) attribute value or raise an
AttributeError exception.
当以正常的方式的访问属性(就是说,要访问的属性既不是实例的属性,也在其所在的类树结构中找不到).name是属性名. 方法应该返回一个属性值,或抛出一个AttributeError异常.
Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __setattr__() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the __getattribute__() method below for a way to actually get total control in new-style classes.
注意如果属性可以通过正常的机制访问, __getattr__()不会被调用(是故意将__getattr__()和_setattr__()设置成不对称的)这样的原因是由于效率并且__setattr__()不能访问实例的其它属性.注意,至少对于实例变量来说, 你可能通过不往实例字典里插入任何值来伪装所有控制(但将它们插入到其它对象中).
self, name, value) |
在属性将被赋值时调用. 这是作为正常机制的代替使用的(就是地实例字典中存储值).name是实例值,vaule是要赋的值.
If __setattr__() wants to assign to an instance attribute, it should not simply execute "self.name = value" -- this would cause a recursive call to itself. Instead, it should insert the value in the dictionary of instance attributes, e.g., "self.__dict__[name] = value". For new-style classes, rather than accessing the instance dictionary, it should call the base class method with the same name, for example, "object.__setattr__(self, name, value)".
如果在__setattr__()内部试图为一个实例属性赋值, 不能简单地执行"self.name = vaule",这会引起对自身的递归调用. 而应该这样, 直接在实例属性字典中插入值,如:"self.__dict__[name] = vaule".
self, name) |
就像__setattr__()一样, 不过其作用是删除而不是赋值.仅仅对于对象用"del obj.name"实现才有意义.