Methods commonly used magic

python common magic methods:
1, __ getattr __ (Self, item): method
when accessing the objects of item attributes, if the object and his parent was not the appropriate properties, methods, we will call this method to deal with . The corresponding property or method call object instance when the corresponding property or method.
Property or method parameter item represents the call.

class Foo:
def __init__(self, x):
self.x = x

@property
def get_01(self):
print(111)
return self.x

__ __getattr DEF (Self, Item):
# fa when an instance of the object attribute is not present operation was performed when the
print ( 'I performed')
Print (Item)
return self.x
F1 = Foo (10)
Print (F1. get_01) # 111,10
Print (f1.a) # I do is, a, 10
Print (f1.get_02) # do is I, get_02, 10

2 .__ setattr __ (self, item , value): method
will block all the attributes of an assignment statement. If you define this method, self.arrt = value will become a self, __ setattr __ ( "attr ", value). This needs attention.
When the properties were in __setattr__ assignment method that can not be used self.attr = value, because he will call again self, __ setattr __ ( "attr ", value), will form an infinite recursive loop,
leading to a stack overflow exception. By indexing operation we should attribute to the dictionary assigned any instances of attributes, i.e. the use of self .__ dict __ [ 'name' ] = value.

class Student:
def __init__(self,item):
self.x=item
def __getattr__(self, item):
return item + ' is not exits'

def __setattr__(self, key, value):
print("执行我")
self.__dict__[key] = value+2


s = Student (10) # # I call the execution method __setattr__
print (SX) # 12 is
print (s.name) Method # call __getattr__ output 'Not exits name IS'
s.age. 1 = # __setattr__ method call
print (s.age) # output. 3

. 3, __ STR __ (Self): automatically invoked method for printing instance of an object
class Student:
DEF the __init __ (Self, Item):
self.x = Item
DEF __str __ (Self):
Print ( "print object when you call ")
return" 111 "

Student = S (10)
Print (S) when the print target call # 111

Guess you like

Origin www.cnblogs.com/laowang-106/p/11353654.html