Original link: https://chegva.com/5303.html
◎Knowledge points
-
The special method of class object __len__()
-
Special methods of class objects __iter__() and __next__()
-
Special methods of class objects __add__() and __radd__()
◎Script practice
▽ The special method of class object __len__()
"""One, the special method of class object __len__()""" """ The built-in function len() is used to return the length of the object """ print(len([1, 2, 3, 4, 5])) # 5 print(len('abcde')) #5 print(len({'a': 1, 'b': 2, 'c': 3})) # 3 """ In the above example, the arguments of the built-in function len() are all instance objects of the built-in class object, for example: [1, 2, 3, 4, 5] is an instance object of the built-in class object list; {'a': 1, 'b': 2, 'c': 3} is an instance object of the built-in class object dict The argument of the built-in function len() cannot be an instance object of a custom class object by default""" # class MyClass(object): # pass # print(len(MyClass())) # TypeError: object of type 'MyClass' has no len() """ If the actual parameter of the built-in function len() can be an instance object of the custom class object, the special method __len__() must be implemented in the custom class object. In this way, when the built-in function len() is called, the special method __len__() of the class object corresponding to the actual parameter will be automatically called internally. The reason why the actual parameter of the built-in function len() can be the instance object of the above built-in class object, This is because the above built-in class objects implement the special method __len__() """ class MyClass(object): def __len__(self): return 18 print(len(MyClass())) #18
▽ Special methods of class objects __iter__() and __next__()
"""Second, the special methods of class objects __iter__() and __next__()""" L = [1, 2, 3, 4, 5] for item in L: print(item) """ The for-in statement cannot be used by default for instance objects of custom class objects""" # class MyClass(object): # pass # for item in MyClass(): # TypeError: 'MyClass' object is not iterable # print(item) """ If you want the for-in statement to work on an instance object of a custom class object, you must implement the special methods __iter__() and __next__() in the custom class object. The for-in statement first calls the special method __iter__() to return an iterable object, Then continuously call the special method __next__() of the iterable object to return the value of the next iteration, until the StopIteration is encountered to exit the loop. Class objects that only implement the special method __iter__() are called iterable class objects; while implementing Class objects with special methods __iter__() and __next__() are called iterator class objects. The reason why the for-in statement can be used for instance objects of some built-in class objects (for example: list, tuple, str, etc.) , It is because these built-in class objects implement the special methods __iter__() and __next__() at the same time """ class MyClass(object): def __init__(self): self.data = 0 def __iter__(self): return self def __next__(self): if self.data > 5: raise StopIteration() else: self.data += 1 return self.data for item in MyClass(): print(item)
▽ Special methods of class objects __add__() and __radd__()
"""Three, the special methods of class objects __add__() and __radd__()""" """ Standard arithmetic operators cannot be used by default on instance objects of custom class objects""" class MyClass1(object): pass class MyClass2(object): pass # TypeError: unsupported operand type(s) for +: 'MyClass1' and 'MyClass2' # print(MyClass1() + MyClass2()) """ If you want standard arithmetic operators to be used on instance objects of custom class objects, you must implement the following special methods for standard arithmetic operators in custom class objects: (1) + The corresponding special methods are __add__() and __radd__() (2) - The corresponding special methods are __sub__() and __rsub__() (3) *The corresponding special methods are __mul__() and __rmul__() (4) / The corresponding special methods are __truediv__() and __rtruediv__() (5) //The corresponding special methods are __floordiv__() and __rfloordiv__() The reason why you can use the addition and multiplication operators to operate the list is because the special methods corresponding to + and * are implemented in the class object list corresponding to the list; The reason why you can use the addition and multiplication operators to operate on strings is because the special methods corresponding to + and * are implemented in the class object str corresponding to the strings. Assuming two operands obj1 and obj2, take + as an example, for obj1 + obj2, you need to implement the special method __add__() in the custom class object corresponding to obj1, or implement the special method in the custom class object corresponding to obj2 __radd__() (r in radd is an abbreviation for right, Because obj2 is to the right of operator +, the special method implemented is __radd__(); because obj1 is to the left of operator +, So the special method implemented is __add__()). """ class C1(object): def __add__(self, other): print("The special method __add__ is called") return "xxx" # return NotImplemented class C2(object): def __radd__(self, other): print("The special method __radd__ was called") return "yyy" # return NotImplemented obj1 = C1() obj2 = C2() print(obj1 + obj2)
◎Script address: https://github.com/anzhihe/learning/blob/master/python/practise/learn-python/python_advanced/special_methods1.py
This article is reprinted from: https://chegva.com/5303.html
This site is for inclusion only, and the copyright belongs to the original author.