Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - What are python magic recipes?
What are python magic recipes?
1.__init__

Initialization magic method

Trigger Timing: Triggered when the object is initialized (not triggered by instantiation, but instantiated in the same operation as).

Parameters: at least one self, receiving object.

Return value: None

Function: Initializes a member of an object.

Note: members initialized in this way are written directly to the object, and classes cannot have.

2.__ New _ _

Instantiating magic method

Trigger Timing: Triggered when a pair is instantiated.

Parameters: At least one cls receives the current class.

Return value: An object instance must be returned.

Roles: instantiating objects

Note: the instantiated Object is the underlying implementation of the Object class, and other classes inherit the __new__ implementation of the object to instantiate the object.

It's okay. Don't touch this magical method. Trigger __new__ before trigger _ __init__.

3.__del__

The Magic of Deconstruction

Trigger Timing: Triggered when the object is useless (without any variable reference).

Parameter: Self-marriage search object

Return value: None

Function: The object used is recycling resources.

Note: del does not necessarily trigger the current method, but only when the current object does not receive any variables.

4.__ Call _ _

Call the magic method of the object.

Trigger Timing: When the function () is called, the object is regarded as a trigger object.

Parameters: at least one self-receiving object, and the rest are determined according to the parameters when calling.

Return value: as the case may be.

Function: It can combine complicated steps and reduce calling steps, which is simple and easy to use.

Note: None.

5.__len__

Trigger timing: triggered when len (object) is used.

Parameter: A parameter itself.

Return value: must be an integer.

Function: It can be set as the number of members of the detection object, but it can also be used for any other operation.

Note: the return value must be an integer, otherwise the syntax will report an error. This requirement is a format requirement.

6.__str__

Trigger timing: trigger when print (object) or str (object) is used.

Parameters: Self-receiving object.

Return value: must be of string type.

Function: print (object time) is used for operation to get a string, which is usually used for shortcut operation.

Note: None.

7.__repr__

Trigger Timing: Triggered when repr (object) is used.

Parameters: Self-receiving object.

Return value: must be a string.

Function: It can be used when converting an object into a string with repr, and it can also be used for shortcut operation.

There is only one difference between repr function and str function when dealing with strings:

The result string of str itself (the result can be executed by eval)

Such as: x =' no graphic carving' str ()-> Without words, Diao

The result string of rerpr defines the structure (eavl will not execute repr results).

Such as: x =' without graphic carving' repr ()-> "Diao has no words"

Note: In a class, the settings of __str__ and __repr__ are usually the same.

eval()

Function executes a string as python code.

Format: eval (string)

Return value: there can be a return value.

8.__bool__

Trigger timing: triggered when bool (object) is used.

Parameters: Self-receiving object.

Return value: must be a Boolean value.

Function: It can be used as a shortcut according to the actual situation.

Note: Only applicable to operations that return Boolean values.

9.__ Format _ _

Trigger timing: when a string. Use formats (objects).

Parameters: one receives an object by itself, and one parameter receives the {0} format in the format, for example: >; five

Return value: must be a string.

Function: Set the object as a parameter of format, and customize the rules of object format.

Note: None.

Descriptor correlation magic method

1.__get__()

Trigger Timing: Triggered when the value of the member attribute of the specified descriptor operation is obtained.

Parameters: 1 descriptor object itself, 2 the object where the attribute described by the descriptor is located, and the class of the object described by the descriptor.

Return value: must exist, otherwise the corresponding attribute value cannot be obtained.

Note: Used only in descriptors.

2.__set__()

Trigger Timing: Triggered when the member property of the specified descriptor operation is set or added.

Parameters: 1 descriptor object itself, 2 the object where the attribute described by the descriptor is located, and 3 the value to be set.

Return value: None

Note: Used only in descriptors.

3.__delete__()

Trigger Timing: Triggered when the member attribute of the specified descriptor operation is deleted.

Parameters: 1 descriptor object itself, 2 the object where the attribute described by the descriptor is located.

Return value: None

Note: Used only in descriptors.

Magical methods related to attribute operations

1.__getattr__()

Trigger Timing: Triggered when a nonexistent object member is obtained.

Parameters: 1 receives the current object itself, and one is a string to get the member name.

Return value: There must be a value.

Role: Sets the value used to access nonexistent attributes.

Note: getattribute will trigger before getattr at any time. If it is triggered, it will not be triggered again.

2.__setattr__()

Trigger Timing: Triggered when the value of an object member is set.

Parameters: 1 self of the current object, one is the member name string to be set and the other is the value to be set.

Return value: No procedure operation

Function: Take over the setting operation and make judgment and verification before setting.

Note: In the current method, members cannot be set directly by using the method of member = value, otherwise it will be infinitely recursive, and the setting method of object must be used.

Object. __setattr__ (parameter 1, parameter 2, parameter 3)

3.__delattr__()

Trigger Timing: Triggered when an object member is deleted.

Parameter: the current object itself.

Return value: None

Role: Members can be verified when they are deleted.

4.__getattribute__()

Trigger timing: triggered when an object member is used, regardless of whether the member exists or not.

Parameters: 1 receive the current object itself, and one is to get the name string of the member.

Return value: must have

Function: When it has encapsulation operation (privatization), it can open some access rights to the program.

5.__dir__()

Trigger timing: triggered when dir (object)

Parameter: 1 receives the current object itself.

Return value: must be of sequence type (list, tuple, collection, etc.). )

Function: You can customize the return value of the member list.

Operate related magic methods (God mode)

Comparison operation related magic method

1.__lt__()

Format:

Def __lt__ (self, other):

Return data

Features:

Trigger timing: trigger automatically when it is less than judgment.

Parameters: The first of the two parameters is self, and the second is the second object of judgment.

Return value: the return value can be of any type, and Boolean value is recommended.

Role: defines the behavior less than the sign X.

2.__le__()

Format:

def __le__(self):

Returns a string

Features:

Trigger timing: trigger automatically when it is judged to be less than or equal to.

Parameters: The first of the two parameters is self, and the second is the second object of judgment.

Return value: the return value can be of any type, and Boolean value is recommended.

Role: defines the behavior less than or equal to the symbol X.

3.__gt__()

Format:

def __gt__(self):

Returns a string

Features:

Trigger timing: trigger automatically when it is judged to be greater than.

Parameters: The first of the two parameters is self, and the second is the second object of judgment.

Return value: the return value can be of any type, and Boolean value is recommended.

Role: define the behavior of greater than sign: x > Y Call x.gt(y).

4.__ge__()

Format:

def __ge__(self):

Returns a string

Features:

Trigger timing: trigger automatically when it is judged to be greater than or equal to.

Parameters: The first of the two parameters is self, and the second is the second object of judgment.

Return value: the return value can be of any type, and Boolean value is recommended.

Role: define the behavior greater than or equal to the symbol: x > = y Call x.ge(y).

5.__eq__()

Format:

def __eq__(self):

Returns a string

Features:

Trigger timing: trigger automatically when the judgment is equal.

Parameters: The first of the two parameters is self, and the second is the second object of judgment.

Return value: the return value can be of any type, and Boolean value is recommended.

Role: define the behavior greater than or equal to the symbol: x == y calls x.eq(y).

6.__ne__()

Format:

def __ne__(self):

Returns a string

Features:

Trigger timing: trigger automatically when it is judged to be unequal.

Parameters: The first of the two parameters is self, and the second is the second object of judgment.

Return value: the return value can be of any type, and Boolean value is recommended.

Function: define the behavior of inequality: x! = y calls x.ne(y)

Magic methods related to arithmetic operation

__add__(self, other) defines the behavior of addition:+

__sub__(self, other) defines the behavior of subtraction:-

__mul__(self, other) defines the behavior of multiplication:

__truediv__(self, other) defines the behavior of true division:/

__floordiv__(self, other) defines the behavior of integer division://

__mod__(self, other) defines the behavior of modular algorithm:%

__divmod__(self, other) defines the behavior when called by divmod ().

__pow__(self, other[, modulo]) defines the behavior when called by power () or operated by * *.

__lshift__(self, other) defines the behavior of bitwise shift to the left:

__rshift__(self, other) defines the behavior of bitwise right shift: >>

__and__(self, other) defines the behavior of bitwise AND operation:&;

__xor__(self, other) defines the behavior of bitwise xor operation:

__or__(self, other) defines the behavior of bitwise OR operation: |

Reverse operation related magic method

__radd__(self, other) is the same as above, and is called when the left operand does not support the corresponding operation.

__rsub__(self, other) is the same as above, and is called when the left operand does not support the corresponding operation.

__rmul__(self, other) is the same as above, and is called when the left operand does not support the corresponding operation.

__rtruediv__(self, other) is the same as above, and is called when the left operand does not support the corresponding operation.

__rfloordiv__(self, other) is the same as above, and is called when the left operand does not support the corresponding operation.

__rmod__(self, other) is the same as above, and is called when the left operand does not support the corresponding operation.

__rdivmod__(self, other) is the same as above, and is called when the left operand does not support the corresponding operation.

__rpow__(self, other) is the same as above, and is called when the left operand does not support the corresponding operation.

__rlshift__(self, other) is the same as above, and is called when the left operand does not support the corresponding operation.

__rrshift__(self, other) is the same as above, and is called when the left operand does not support the corresponding operation.

__rand__(self, other) is the same as above, and is called when the left operand does not support the corresponding operation.

__rxor__(self, other) is the same as above, and is called when the left operand does not support the corresponding operation.

__ror__(self, other) is the same as above, and is called when the left operand does not support the corresponding operation.

Magic methods related to assignment operation

__iadd__(self, other) defines the behavior of assignment addition:+=

__isub__(self, other) defines the behavior of assignment subtraction:-=

__imul__(self, other) defines the behavior of assignment multiplication: =

__itruediv__(self, other) defines the behavior of allocating true division:/=

__ifloordiv__(self, other) defines the behavior of assignment integer division://=

__imod__(self, other) defines the behavior of the assignment module algorithm:% =

__ipow__(self, other[, modulo]) defines the behavior of assignment power operation: * * =

__ilshift__(self, other) defines the bitwise left shift behavior of assignment:

__irshift__(self, other) defines the bitwise right shift behavior of assignment: >>=

__iand__(self, other) defines bitwise operation behavior of assignment:&; =

__ixor__(self, other) defines the behavior of bitwise xor operation of assignment: =

__ior__(self, other) defines the behavior of bitwise or operation of assignment: | =

Unary operation related magic method

__pos__(self) defines the behavior of the plus sign:+x.

__neg__(self) defines the behavior of minus sign:-x.

__abs__(self) defines the behavior when called by abs ().

__invert__(self) defines the behavior of bitwise inversion: ~x

Type conversion related magic ginger

__complex__(self) defines the behavior when complex () is called (an appropriate value needs to be returned).

__int__(self) defines the behavior when called by int () (an appropriate value needs to be returned).

__float__(self) defines its behavior when it is called by float () (an appropriate value needs to be returned).

__round__(self[, n]) defines the behavior when round () is called (an appropriate value needs to be returned).

__index(self)__ 1。 When objects are applied in slice expressions, plastic modeling is realized.

2. If you define a custom numeric type that can be used in slicing, you should define index.

3. If an index is defined, you need to define an int and return the same value.

Magic methods related to context management

__enter__ () and __exit__ ()

Enter (oneself)

1. defines the initialization behavior when using the with statement.

2. The return value of 2.enter is bound by the target of the with statement or the name after as.

Exit (self, exctype, excvalue, traceback)

1. defines what the context manager should do when the code block is executed or terminated.

2. It is usually used to handle exceptions, clean up work or do some daily work after the code block is executed.

Magic methods related to container types

__len__(self) defines the behavior when called by len () (returns the number of elements in the container).

__getitem__(self, key) defines the behavior of getting the specified element in the container, which is equivalent to self[key].

__setitem__(self, key, value) defines the behavior of the specified element in the setting container, which is equivalent to self[key] = value.

_ _ item _ _ (self, key) defines the behavior of deleting the specified element in the container, which is equivalent to del self[key].

__iter__(self) defines the behavior of the elements in the container during iteration.

__reversed__(self) defines the behavior when reversed () is called.

__contains__(self, item) defines the behavior (in or not in) when using the member test operator.

Classification: python Object-Oriented