Type conversion magic
Type conversion magic is actually the result of implementing factory functions such as str and int. Usually these functions also have type conversion functions. Here are some related magic methods:
•__int__(self)
•Convert to integer type, corresponding to int function.
•__long__(self)
•Convert to long integer type, corresponding to long function.
•__float__(self)
•Convert to floating point type, corresponding to float function.
•__complex__(self)
•Convert to complex number type, corresponding to the complex function.
•__oct__(self)
•Convert to octal, corresponding to the oct function.
•__hex__(self)
•Convert to hexadecimal, corresponding to the hex function.
•__index__(self)
•First, this method should return an integer, which can be int or long. This method is valid in two places. First, the value obtained by the index function in the operator module is the return value of this method. Second, it is used for slicing operations. The following code demonstration will be done specifically.
•__trunc__(self)
•Called when math.trunc(self) is used. __trunc__ returns an integer truncation of the self type (usually a long integer).
•__coerce__(self, other)
•Implemented type coercion. This method corresponds to the result of the coerce built-in function (this function has been removed since Python 3.0, which means that this magic method is meaningless. As for whether subsequent versions will add support again, it depends Depends on official )
•The function of this function is to forcefully convert two different numerical types into the same type, for example:
Themethod returns a primitive, corresponding to the two converted numbers. Its priority is: complex number > floating point number > long integer > integer. During conversion, it will be converted to the type with higher priority among the two parameters. When the conversion cannot be completed, a TypeError is triggered.
And when we define this magic method, if the conversion cannot be completed, it should return None.
There is an important mechanism here. When python performs an operation, such as 1 + 1.0, it will first call the coerce function to convert it to the same type, and then run it. This is why 1 + 1.0 = 2.0, because The actual operation after conversion is 1.0 +1.0. It is not surprising to get such a result.
Code example:
class Foo(object): def __init__(self, x): self.x = x def __int__(self): return int(self.x) + 1 def __long__(self): return long(self.x) + 1 a = Foo(123) print int(a) print long(a) print type(int(a)) print type(long(a))
One thing to note here is that the return value of the magic method must meet expectations. For example, __int__ should return an int type. If we return other types arbitrarily, such as string (str), list (list), etc., an error will be reported. .
def __int__(self): return str(self.x)
def __int__(self): return list(self.x)
But int can return long, and long will be automatically processed into long when it returns int:
class Foo(object): def __init__(self, x): self.x = x def __int__(self): return long(self.x) + 1 def __long__(self): return int(self.x) + 1 a = Foo(123) print int(a) print long(a) print type(int(a)) print type(long(a))
The above happened on python2.7.11. This is such a strange behavior that I think it may be a BUG. In short, we should pay attention to returning the corresponding type when using it to avoid errors.
__index__(self):
First of all, it corresponds to operator.index(), operator.index(a) is equivalent to a.__index__():
import operator class Foo(object): def __init__(self, x): self.x = x def __index__(self): return self.x + 1 a = Foo(10) print operator.index(a)
Another special effect that is amazing when used in a sequence:
class Foo(object): def __init__(self, x): self.x = x def __index__(self): return 3 a = Foo('scolia') b = [1, 2, 3, 4, 5] print b[a] print b[3]
Can be used as an index and can perform slicing operations:
class Foo(object): def __init__(self, x): self.x = x def __index__(self): return int(self.x) a = Foo('1') b = Foo('3') c = [1, 2, 3, 4, 5] print c[a:b]
In fact, the function slice used inside the slice processes it. Interested students can learn about this function:
a = Foo('1') b = Foo('3') c = slice(a, b) print c d = [1, 2, 3, 4, 5] print d[c]
__coerce__(self, other):
Code example:
class Foo(object): def __init__(self, x): self.x = x def __coerce__(self, other): return self.x, str(other.x) class Boo(object): def __init__(self, x): self.x = x def __coerce__(self, other): return self.x, int(other.x) a = Foo('123') b = Boo(123) print coerce(a, b) print coerce(b, a)
Summary: It is a magic method that calls the first parameter.
class:
The representation of the class is actually the external characteristics. For example, when using the print statement, what is printed is actually the output of the corresponding function:
•__str__(self)
•Define the behavior to occur when str() is called on an instance of your class. Because print calls the str() function by default.
•__repr__(self)
•Define the behavior to occur when repr() is called on an instance of your class. The main difference between str() and repr() is their target group. repr() returns machine-readable output, while str() returns human-readable output. The repr() function is called by default in exchange mode
•Function.
•__unicode__(self)
•Define the behavior to occur when unicode() is called on an instance of your class. unicode() is similar to str(), but returns a unicode string. Note that if str() is called on your class but you only define __unicode__() then it will not
•Work. You should define __str__() to ensure that the correct value is returned when called, not everyone is in the mood to use unicode().
•__format__(self, formatstr)
• Define the behavior that occurs when an instance of your class is used to format using the new format string methods. For example, "Hello, {0:abc}!".format(a) will cause a.__format__("abc") to be called. This is great for defining your own numeric or string types
• is very meaningful, you may give some special formatting options.
•__hash__(self)
•Define the behavior to occur when hash() is called on an instance of your class. It must return an integer for fast comparison in a dictionary.
•Please note that when implementing __hash__ you usually also implement __eq__. There is the following rule: a == b implies hash(a) == hash(b) . In other words, the return values of the two magic methods should be consistent.
•The concept of ‘hashable object’ is introduced here. First, the hash value of a hashable object should be unchanged during its life cycle, and to obtain the hash value means implementing the __hash__ method. Hash objects are comparable, which means implementing __eq__ or
•The __cmp__ method, and if the hash objects are equal, their hash values must be equal. To implement this feature means that the return value of __eq__ must be the same as __hash__.
•Hashable objects can be used as dictionary keys and collection members, because these data structures use hash values internally. All built-in immutable objects in python are hashable, such as tuples, strings, numbers, etc.; while mutable objects cannot be hashed, such as lists,
•Dictionaries and more.
•Instances of user-defined classes are hashable by default and are not equal to anyone but themselves, since their hash value comes from the id function. But this does not mean hash(a) == id(a), please pay attention to this feature.
•__nonzero__(self)
•Define the behavior to occur when bool() is called on an instance of your class. This method should return True or False, depending on the value you want it to return. (Changed to __bool__ in python3.x)
•__dir__(self)
•Define the behavior to occur when dir() is called on an instance of your class. This method should return a list of properties to the user.
•__sizeof__(self)
•Define the behavior to occur when sys.getsizeof() is called on an instance of your class. This method should return the size of your object in bytes. This usually makes more sense for Python classes implemented as C extensions, which can be helpful in understanding these extensions.
There is nothing particularly difficult to understand here, so the code example is omitted.
The above python magic method - detailed explanation of attribute conversion and class representation is all the content shared by the editor with you. I hope it can give you a reference, and I hope you will support Script Home.