Examples of special methods for advanced Python learning and details of advanced python Learning
Preface
I recently learned a special method that I have never touched before when I was learning python.
What is a special method? When designing a class, python has a Initialization Method $ __init __$, which is similar to the constructor in java. This is a special method, also called a magic method. In simple terms, special methods can add some magical features to the classes you design, such as native python slicing, iteration, and multiplication operations. In python, special methods start with double underscores and end with double underscores.
A big example
There is a concept in mathematics that represents a number called a vector, but there is no data type in python. Let's try to implement it in python.
First, consider that a vector is different from a common data type. A traditional number can be operated directly, while a vector needs to perform separate operations on different coordinates. To try.
First, define a class to implement the initialization method.
# Implement Vector type class Vector: def _ init _ (self, x = 0, y = 0): self. x = x self. y = y
How can we add vectors? In a two-dimensional vector, the addition of a vector is the result of adding each coordinate separately. There is a $ __add __$ method in python to perform addition operations.
Class Vector: def _ init _ (self, x = 0, y = 0): self. x = x self. y = y # implement vector addition def _ add _ (self, other): x = self. x + other. x y = self. y + other. y return Vector (x, y)
We add the x and y variables respectively, and then return the Vector. In python, you can directly splice strings with addition. In this case, python implements the add method for strings.
The addition is implemented. The multiplication principle is the same. You can multiply each coordinate separately.
Class Vector: def _ init _ (self, x = 0, y = 0): self. x = x self. y = y # implement vector addition def _ add _ (self, other): x = self. x + other. x y = self. y + other. y return Vector (x, y) # implement Vector multiplication, for example, r * 3 def _ mul _ (self, scalar): return Vector (self. x * scalar, self. y * scalar)
When we perform vector operations, another common operation is to evaluate the vector model. We use the special method $ __abs __$. abs is generally used to obtain the absolute value of a number, the vector is not used, which is suitable for finding the modulus. Use the hypot method in the math module to calculate $ \ sqrt (x ^ 2 + y ^ 2) $.
Class Vector: def _ init _ (self, x = 0, y = 0): self. x = x self. y = y # True/false value. If the vector modulus is 0, false def _ bool _ (self): return bool (abs (self) is returned )) # implement vector addition def _ add _ (self, other): x = self. x + other. x y = self. y + other. y return Vector (x, y) # implement Vector multiplication, for example, r * 3 def _ mul _ (self, scalar): return Vector (self. x * scalar, self. y * scalar) # Return vector modulo # hypot () returns euclidean norm sqrt (x * x + y * y) def _ abs _ (self ): return hypot (self. x, self. y)
Find an example to run.
v = Vector(2, 3)print(v)v2 = Vector(4, 5)print(v+v2)print(v+v2*2)
<__main__.Vector object at 0x000002B4B1843C50><__main__.Vector object at 0x000002B4B1843EF0><__main__.Vector object at 0x000002B4B1843898>
It can be run. It seems to be correct, but the output result is very strange. What should I do? Python has a special $ __repr __$ method. You can modify the output style on the console.
Class Vector: def _ init _ (self, x = 0, y = 0): self. x = x self. y = y # True/false value. If the vector modulus is 0, false def _ bool _ (self): return bool (abs (self) is returned )) # implement vector addition def _ add _ (self, other): x = self. x + other. x y = self. y + other. y return Vector (x, y) # implement Vector multiplication, for example, r * 3 def _ mul _ (self, scalar): return Vector (self. x * scalar, self. y * scalar) # Return vector modulo # hypot () returns euclidean norm sqrt (x * x + y * y) def _ abs _ (self ): return hypot (self. x, self. y) # implement _ repr _ method. When printing a Vector on the console, the Vector (1, 2) # implement _ str __, using str () returns the string def _ repr _ (self): return 'vector (% r, % r) '% (self. x, self. y)
After implementing the $ __repr __$ method, we can output Vecotor (x, y) on the console ). The corresponding $ __str __$ method returns the corresponding string using str () and is displayed to the user.
Now let's take a look at the results of the previous program running.
v = Vector(2, 3)print(v)v2 = Vector(4, 5)print(v+v2)print(v+v2*2)print(abs(v))
Vector(2, 3)Vector(6, 8)Vector(10, 13)3.605551275463989
Good results.
By implementing special methods, custom types can behave the same as built-in types, so that we can write code with a more python style.
In addition to the special methods mentioned above, python has more than 80 special methods. For example, the $ __len __$ method can be used to evaluate the length, $ __getitem __$ you can use operations such as haha [2] for slicing and iteration, and $ __setitem __$.
Summary
The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.