Python magic methods-comparison and python magic
Python 2.x supports comparison of different types. The comparison principles are as follows:
Built-in type:
1. Same type: 1.1) numeric type: Contains int, float, long, complex, bool (bool type is a subclass of int, and True = 1, False = 0 ). Compare the values by number, for example:
{} <''Is equivalent to 'dict '<'str'. The class name is converted to a string and then compared according to the string principle.
# Coding: UTF-8 and # coding = gbk strings are encoded differently, so there will be differences. However, Comparison between Chinese characters is rarely performed.
The comparison method between a set and a sequence is similar.
2. Comparison between dictionaries:
In fact, the dictionary is similar to the sequence and also compared one by one, but the dictionary isKeyIt is not a value, and the dictionary is unordered, so the order of comparison is difficult to predict. Therefore, comparison between dictionaries is not recommended in any case.
Version differences:
Because the comparison between different built-in types is not in line with human intuition, and the behavior is weird, it is difficult to estimate. So in python3.xCancelSupports comparison between different built-in types. For example, when comparing int and str in python3.x, an exception is thrown directly.
Custom class:
1. inherit from the basic type and do not override the relevant magic method, then compare according to the above built-in type principle.
2. Custom classes, but related magic methods are not overwritten. Then, new classes> classic classes; new classes are compared by class name; classic classes are compared by the return value of the id function.
3. As long as the corresponding magic method is rewritten, the results are returned Based on the return value of the magic method. Whether or not it is inherited from the basic type.
Related magic methods:
_ Cmp _ (self, other): corresponds to the built-in function cmp of python, which should be returned when self> otherPositive Integer; Self = other, return0; When self <other,Negative integer. (This method is removed from python3.x because it is redundant with the following method .)
Example:
class Foo(str): def __new__(cls, word): return str.__new__(cls, word) def __cmp__(self, other): if ('scolia' in self) and ('scolia' in other): return 0 elif 'scolia' in self: return 1 else: return -1a = Foo('scolia')b = Foo('scolia123')c = Foo('good')d = Foo('Good')print cmp(a, b)print cmp(b, c)print cmp(c, d)
In this example, I define that all strings with substrings 'scolia 'Return 0. If one string has only one and some strings serveFirstWhen the parameter is set, 1 is returned. If neither of them is returned,-1 is returned.
That is to say, the first parameter of the cmp function is self, and the second parameter is other.
Of course, cmp also has a hidden feature. When two parameters are the same object, 0 is directly returned regardless of the internal _ cmp _ logic. For example:
c = Foo('good')d = cprint cmp(c, d)
C and d do not contain the string 'scolia 'according to the logic of the code written by the user. The-1 is returned, but the result is actually 0. Description cmp FunctionsSame objectIs to directly give the results without the magic method.
_ Eq _ (self, other)
Defines the behavior of equal symbols, =
_ Ne _ (self, other)
Defines unequal characters ,! =
_ Lt _ (self, other)
Defines behavior that is less than the symbol, <
_ Gt _ (self, other)
Define actions greater than symbols,>
_ Le _ (self, other)
Defines the behavior of less than or equal to the symbol, <=
_ Ge _ (self, other)
Defines the behavior of symbols greater than or equal to,> =
All the above magic methods must return oneBoolean Value.
For example:
class Foo(str): def __new__(cls, word): return str.__new__(cls, word) def __eq__(self, other): if ('scolia' in self ) and ('scolia' in other): return True else: return Falsea = Foo('scolia')b = Foo('scolia123')print a == b
Therefore, these magic methods actually reload the corresponding symbols. For example, Here =, the left is equivalent to self, and the right is equivalent to other. You can perform logical orchestration as needed.
For example:
class Foo(str): def __new__(cls, word): return str.__new__(cls, word) def __gt__(self, other): return len(self) > len(other) def __lt__(self, other): return len(self) < len(other) def __ge__(self, other): return len(self) >= len(other) def __le__(self, other): return len(self) <= len(other)
Here, multiple comparison operators are reloaded. The core is to compare the strings by length. The longer the comparison, the bigger the comparison. It seems that an expression is returned, but the function will calculate the expression when actually returning it, that is, the return is actually a Boolean value.
There is no reload comparison operator. For example, if there is no reload _ eq _ =, the method of its parent class will be automatically called, which is also in line with our inherited concept.
What if it is compared with the basic type:
class Foo(str): def __new__(cls, word): return str.__new__(cls, word) def __eq__(self, other): if ('scolia' in self ) and ('scolia' in other): return True else: return Falseb = Foo('scolia')a = 'scolia123'print a == bprint b == a
It seems to be based on our own method, regardless of the order on both sides.
What if two custom classes conflict:
class Foo(str): def __new__(cls, word): return str.__new__(cls, word) def __eq__(self, other): if ('scolia' in self ) and ('scolia' in other): return True else: return Falseclass Boo(str): def __new__(cls, word): return str.__new__(cls, word) def __eq__(self, other): if ('scolia' in self ) and ('scolia' in other): return False else: return Truea = Foo('scolia')b = Boo('scolia')print a == bprint b == a
At this time, who is on the left of the = sign, the rules of who will be applied.
Here we will discuss the magic methods for comparison. You are welcome to discuss them.
Related references: click here