This is the 25th day of my participation in Gwen Challenge

1. An overview of the

In Python classes, double strokes are added before and after the names of some methods and properties. These methods and properties are usually special Python methods and properties. Developers can override these methods or call them directly to implement special functions.

We’ve already seen the __init__() constructor for special methods, and developers can override the __init__ method to implement their own initialization logic.

methods instructions example
__init__ A constructor Object creation
__del__ destructor Destruction of objects
__repr__ , __ str __ Print, convert print(a)
__call__ A function call a()
__getattr__ The dot operation a.XXX
__setattr__ Attribute assignment a.xxx = value
__getitem__ The index operation a[key]
__setitem__ The index assignment a[key] = value
__len__ The length of the len(a)

Each operator actually corresponds to a method.

The operator Special methods instructions
The operator + __add__ add
The operator – __sub__ subtraction
<, < =, = = __lt__ .__le__.__eq__ Comparison operator
>, > =,! = __gt__.__ge__ , __ ne __ Comparison operator
I,^,& __or__ .__ xor __ ,__ and __ Or, xor, and
< < > > __lshift__ , __rshift__ Move left, move right
*, /, %, // __mul__ .__truediv__ .__mod__ ,__floordiv__ Multiply, float division, cross operation (mod), integer division
支那 __pow__ Index of operation

2. Rewrite __repr__

By default, __repr__() returns the “class name +object at+ memory address” information associated with the instance object

  • __reper__(self) has the same properties as __init__(self), every class in Python contains the __repr__() method, because the object class contains the __reper__() method, All classes in Python inherit directly or indirectly from the Object class.

  • Print (instance object name) is the same as print(instance object name.__repr__()), and the output is the same (memory address may be different).

  • If we want to learn more about the instantiated object, we can override the class’s __repr__() method

Class Animal: def __init__(self,name,food): # Animal: def __repr__(self): Return "Animal[=name"+self. Name +"likefood="+self. Food +"]" print(Cat)Copy the code

3. Rewrite the __call__

Class instance method __call__(), which functions like overloading the () operator in a class so that class instance objects can be used as “object names ()” just like ordinary functions are called

For callable objects, “class instance object name ()” can actually be understood as a shorthand for the class instance object name.__call__()

class Animal: def __call__(self,name,food): Print (" {0} call __call__ method like to eat {1} ". The format (name, food) Cat = Animal () the __call__ (" Tom "and" fish ") the Cat (" Tom "and" fish ")Copy the code

4. Rewrite hasattr/getattr/setattr

Python has properties and methods that provide the ability to determine/get/set the specific name of a class instance object.

  • Hasattr () to determine whether the class instance object contains the specified property name or method and returns a Boolean value of True or False
  • Getattr () to get the value of the specified property in the instance object
  • Setattr () adds a property/method dynamically if the specified property/method does not exist, and overwrites the value of the specified property if it does
Class Animal: def __init__(self,name,food): # def get_age(self): Print ("{0} age is {1} age ". Format (self.__name,self.age)) Cat = Animal("Tome","fish" Print (hasattr(Cat,"name")) print(hasattr(Cat,"food")) # print(hasattr(Cat,"name")) print(hasattr(Cat,"food") Print (getattr(Cat," name","BOb") print(cat.name)Copy the code

5. Operator overload

Python everything is an object, and every clock sequence is a Python class, such as list(),dict(), and so on

Python internally uses a technique of overloading operators to implement operator-specific processing. When an instance object performs an operator operation, the system can call the corresponding method in the class to handle it

class Person: def __init__(self, name): self.name = name def __add__(self, other): If isinstance(other, Person): return "{0}-- {1}". Format (self.name,other.name) else: P1 = Person("Tom") P2 = Person("Bob") Sum = P1+P2 print(Sum)Copy the code

conclusion

Python provides default methods starting with a double underscore to help you create instance objects, initialize instance object properties, override methods, view class properties, get instance object property values, and so on

These methods can also be overridden as needed when creating a new class.

Ok, that’s the content of this issue, welcome to the comments section, see you next time ~