Python magic method-Explanation of attribute conversion and class expression, and explanation of python

Source: Internet
Author: User
Tags hashable list of attributes

Python magic method-Explanation of attribute conversion and class expression, and explanation of python

Type conversion magic

The magic of type conversion is actually the result of implementing factory functions such as str and int. Usually these functions also have the function of type conversion. Below are some related magic methods:

• _ Int _ (self)

• Convert to an integer, corresponding to the int function.

• _ Long _ (self)

• Convert and grow an integer, corresponding to the long function.

• _ Float _ (self)

• Convert to float type, corresponding to float function.

• _ Complex _ (self)

• Convert to the plural type, corresponding to the complex function.

• _ Oct _ (self)

• Convert to octal, corresponding to the oct function.

• _ Hex _ (self)

• Convert to hexadecimal format, corresponding to hex function.

• _ Index _ (self)

• First, this method should return an integer, which can be int or long. This method is effective in two places. The value obtained by the index function in the operator module is the return value of this method, and the value obtained by the index function is used for slicing. The following code is used for demonstration.

• _ Trunc _ (self)

• When math. trunc (self) is used, it is called. _ trunc _ to return integer truncation of its own type (usually a long integer ).

• _ Coerce _ (self, other)

• Forced type conversion is implemented. This method corresponds to the result of the coerce built-in function (python3.0 begins to remove this function, that is, this magic method is meaningless, it depends on the official version .)

• This function is used to forcibly convert two different numeric types into the same type, for example:

Method returns a ancestor corresponding to the converted two numbers. Its priority is: plural> floating point> long integer> integer. During conversion, it is converted to the type with the highest priority among the two parameters. If the conversion fails, a TypeError is triggered.

When we define this magic method, if the conversion cannot be completed, we should return None.

There is an important mechanism here. When python is performing computation, for example, 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.

Sample Code:

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) + 1a = Foo(123)print int(a)print long(a)print type(int(a))print type(long(a))

Note that the return value of the magic method must meet the expectation. For example, _ int _ should returnIntType. If other types such as string (str) and list are returned, an error is returned.

def __int__(self):    return str(self.x)

def __int__(self):    return list(self.x)

However, int can return long, while long will be automatically processed as long when int is returned:

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) + 1a = Foo(123)print int(a)print long(a)print type(int(a))print type(long(a))

The above occurs on python2.7.11. This is a strange behavior, so 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, it corresponds to operator. index (). operator. index (a) is equivalent to a. _ index __():

import operatorclass Foo(object):  def __init__(self, x):    self.x = x  def __index__(self):    return self.x + 1a = Foo(10)print operator.index(a)

The other is an amazing special effect when used in sequence:

class Foo(object):  def __init__(self, x):    self.x = x  def __index__(self):    return 3a = Foo('scolia')b = [1, 2, 3, 4, 5]print b[a]print b[3]

Slice can be used as an index:

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, slice is used internally to process slice. If you are interested, you can learn about this function:

a = Foo('1')b = Foo('3')c = slice(a, b)print cd = [1, 2, 3, 4, 5]print d[c]

_ Coerce _ (self, other ):

Sample Code:

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)

Conclusion: It is the magic method that calls the first parameter.

Class representation:

Class representation is actually an external feature. For example, when a print statement is used, what is printed is actually the output of the corresponding function:

• _ Str _ (self)

• Defines the behavior that occurs when str () is called by an instance of your class. Because print calls the str () function by default.

• _ Repr _ (self)

• Defines the behavior that will occur when the repr () is called by an instance of your class. The main difference between str () and repr () is its target group. Repr () returns the machine-readable output, while str () returns the human-readable output. The repr () function is called by default in switching mode.

• Functions.

• _ Unicode _ (self)

• Defines the behavior that occurs when unicode () is called by an instance of your class. Unicode () is similar to str (), but returns a unicode string. Note: If you call str () for your class, but you only define _ unicode _ (), it will not

• Work. You should define _ str _ () to ensure that the correct value is returned during the call. Not everyone is in the mood to use unicode ().

• _ Format _ (self, formatstr)

• Defines the behavior that occurs when an instance of your class is used to format strings in a new format. For example, "Hello, {0: abc }! ". Format (a) will call a. _ format _ (" abc "). This defines your own value or string type

• It is very meaningful. You may give some special formatting options.

• _ Hash _ (self)

• Defines the behavior that will be generated when hash () is called by an instance of your class. It must return an integer for quick comparison in the dictionary.

• When implementing _ hash _, _ eq _ is also required __. The following rule applies: a = B implies hash (a) = hash (B ). That is to say, the returned values of the two magic methods are best consistent.

• Here we introduce the concept of a 'hashable object'. First, the hash value of a hashable object should remain unchanged during its lifecycle, to obtain the hash value, we need to implement the _ hash _ method. The hash objects can be compared, which means that _ eq _ or

• The operator _ cmp _ method, while the hash object must have the same hash value, to implement this feature, the return value of _ eq _ must be the same as that of _ hash.

• The hash object can be used as a key and a member of the dictionary, because the hash value is used inside the data structure. All built-in unchanged objects in python can be hashed, such as tuples, strings, and numbers. variable objects cannot be hashed, such as lists,

• Dictionary.

• User-defined class instances can be hashed by default, and no one except them is equal because their hash value comes from the id function. However, this does not mean hash (a) = id (a). Pay attention to this feature.

• _ Nonzero _ (self)

• Define the behavior that bool () will take when it is called by an instance of your class. This method should return True or False, depending on the value you want it to return. (Change to _ bool _ in python3.x __)

• _ Dir _ (self)

• Defines the behavior that is generated when dir () is called by an instance of your class. This method should return a list of attributes to the user.

• _ Sizeof _ (self)

• Defines the behavior that sys. getsizeof () is called by an instance of your class. In bytes, this method returns the size of your object. This is usually more meaningful for Python classes implemented in the form of C extensions, which helps to understand these extensions.

There is nothing really hard to understand here, so the code example is skipped.

The above python magic method-attribute conversion and class expression details are all the content that I have shared with you. I hope you can give us a reference, and I hope you can also provide more support for the customer's house.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.