Home Backend Development Python Tutorial Python magic method-detailed explanation of attribute conversion and class representation

Python magic method-detailed explanation of attribute conversion and class representation

Aug 04, 2016 am 08:55 AM
python magic method

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:

The

method 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))
Copy after login

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)
Copy after login

def __int__(self):
    return list(self.x)
Copy after login

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))
Copy after login

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)
Copy after login

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]
Copy after login

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]
Copy after login

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]
Copy after login

__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)
Copy after login

Summary: It is a magic method that calls the first parameter.

Representation of

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.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

See all articles