The paper contains 4790 words and is expected to last 14 minutes
Photo source: Unsplash
Learn a few tricks to maximize the performance of your Python programs while avoiding unnecessary waste of resources. For example, using magic methods in Python can improve code performance. Today, we will teach you to improve the performance of Python programs “magic”, come to learn ~
What are Magic Methods?
Magic methods are concepts in object-oriented Python programming. There are many special ways you can define categories to add “magic” to them.
Magic methods are always surrounded by double underscores, such as __ init __. Nor are they adequately documented. All of Python’s magic methods are documented in the same part of the Python documentation, scattered and loosely organized. There are few examples to be found in this section.
What are the magic methods?
To address the lack of documentation for magic methods, I’ve put together some simple examples of how to use Python magic methods.
Photo source: Unsplash
1. Create a dict object that accepts only integers and floating-point numbers as its values
Start by creating a virtual use case. In this case, I want to create a class that can create dictionary objects that only accept integers or floating-point numbers as their values.
If any other data types such as strings, lists, and tuples are added as values to a custom dictionary object, an exception is thrown, prompting the user that the custom dict object can only accept integers and floating-point numbers.
To achieve the above, use the following magic method:
__int __, __ setitem __ and __str__
First create a custom class called CustomIntFloat, and then pass the dict to the parameter inheritance list. This means that, except where you choose to modify this behavior, the creation of the object will behave essentially the same as the dictionary.
Then create a __ init __ method to construct the CustomIntFloat dict object. The argument list for this object contains keys and values, which are set to type “None” by default. The reason is that if a user creates an object of the CustomIntFloat class without passing a key or value, an empty dict is created. I created a simple condition that if the key is not passed, the key argument is assigned to “None” by default, and an empty dict is created by referring to the CustomIntFloat object with the class attribute EMPty_dict.
Next, if the user specifies a key of length 1 and a corresponding value for an int or float class instance, the key and value are set in the object.
Finally, in the else statement, if the user specifies multiple keys and values as iterable, the zip function is used to compress the iterable and assign it the variable name zipped. Finally, iterate over the compressed value and check whether the value is of type int or float. If not, CustomIntFloatError is raised.
2. CustomIntFloatError Exception class and __str__ magic method
When you raise the CustomIntFloatError exception, you are actually creating an instance of the CustomIntFloatError class and printing it at the same time.
Therefore, this custom error class requires __ init __ and __str__ magic methods. In this example, you take the passed value and set it to an attribute value in the CustomIntFloatError class.
This means that when the program reports an error, the init value passed to CustomIntFloat can be set to an attribute in the CustomIntFlower class (self.value), which is easy to check.
If an invalid input is specified, a CustomIntFloatError exception is raised and the object is not constructed. A useful error message tells the user that only integers and floating point numbers are valid.
Similarly, when you try to instantiate object Z (commented out) with multiple keys and values, the same exception is thrown, notifying the user that there are “three” invalid inputs.
- # z = CustomIntFloat (key= [‘a’, ‘b’, ‘c’], value= [1, 2, ‘three’])
- Avdeev = CustomIntFloat (key= [‘A’, ‘B’, ‘C’], value= [1, 2, 3])
3. __ setitem __ Magic method
The __setitem __ magic method is called when keys and values are set in the dictionary. Once the CustomIntFloat object is constructed, the same CustomIntFloatError exception will be raised if the user tries to add a value that is not of int or float type. A code snippet has been added below that shows how to set keys and values as expected.
- x = CustomIntFloat(‘a’, 1)
- print(type(x))
- X [‘ b ‘] = 2.1
- print(x)
- # x[‘c’] = ‘Three’
Invalid input causes a CustomIntFloatError exception to be raised, as shown below.
- classCustomIntFloatError(Exception):
- def__init__(self, value):
- self.value = value
- def__str__(self):
- returnself.value +’ is not valid\nOnly Integers and floats are valid values \nin CustomIntFloat(dict) ‘
- classCustomIntFloat(dict):
- empty_dict = {}
- def__init__(self, key=None, value=None):
- if key isNone:
- CustomIntFloat.empty_dict = {}
- eliflen(key) ==1andisinstance(value, (int, float)):
- dict.__setitem__(self, key, value)
- else:
- zipped =zip(key, value)
- for tup in zipped:
- ifisinstance(tup[1], (int, float)):
- dict.__setitem__(self, tup[0], tup[1])
- else:
- raise CustomIntFloatError(tup[1])
- def__setitem__(self, key, value):
- ifnotisinstance(value, (int, float)):
- raise CustomIntFloatError(value)
- returndict.__setitem__(self, key, value)
4. Summary of the CustomIntFloat class
Photo source: Unsplash
With built-in class inheritance like Dict, custom behavior can be reimplemented through magic methods. This has many benefits.
Importantly, users don’t need to learn any new syntax. When users want to add keys and values to a CustomIntFloatdict object, they simply do so in the usual way. The only difference is that only int and float values are allowed. If the user specifies any other type, the custom error message effectively indicates the user where the error occurred and the expected value type.
Quick-fire magic method
Examples using mathematical operators
__sub__, __add__, and __ MUL __ (a custom __repr__)
You can also use magic methods in Python’s math operators to see how magic methods are used, such as __add__, __sub__, and __MUL __ created in custom objects.
Operators like +, -, /, and * are polymorphic methods. As shown in the Python Prompt below, the plus sign (+) is polymorphic and can be used to concatenate strings, adding integers and a list of combinations. This is possible because all of these types (STR, list, and int) have an Add method in their respective classes. Python simply converts the + symbol to an __add__ method on the calling object (see the example below).
This means that if you include an __add__ method in a class, you can use the + sign in your own object.
Class magic method operator
Here, create a class named NumOperations. This class creates NumOperations objects. When the user of NumOperations passes the list to the argument list of __init __, the list is set to a property in the NumOperations object and named math_list.
When NumOperations objects (S) are built, it is easy to use magic methods and define objects and broadcast mathematical operations.
In more detail, the magic method __sub__ takes two NumOperations objects and compresses their list together, iterating over the list of other corresponding tuples. Subtract the second element from the first tuple and append the value to a new list named minuslst, passing it as a parameter to the NumOperations constructor.
The return value is now a new NumOperations object.
Using the __sub__ method to perform this broadcast means we can use the minus (-) operator.
Use the magic method __ repr __ again to return the string of the list set in the new object. At the same time, this has been modified so that when the user gets two NumOperations object outputs it expects.
This is a list where the elements have been subtracted from each other;
[90,81,72,63,54]
__add__ and __MUL __ both have a similar method operation, __sub__, but use list understanding to cut down the necessary lines of code.
Subtraction, addition, and multiplication magic methods have been defined in advance to use custom NumOperation objects.
This broadcast behavior is similar to the broadcast behavior in data analysis packages such as Pandas and Numpy.
The __add__ and __MUL __ methods both have two NumOperations objects. This means that users can use both the plus operator + and the multiplication operator *. As you can see in the following example, q is the result of x * y, which returns a new NumOperations object. When we print q, we have the string representation of the broadcast operation as a list.
- classNumOperations(object):
- def__init__(self, math_list):
- self.math_list = math_list
- def__sub__(self, other):
- minuslst = []
- zipped =zip(self.math_list, other.math_list)
- for tup in zipped:
- minuslst.append(tup[0] – tup[1])
- return NumOperations(minuslst)
- def__add__(self, other):
- addlst = [x + y for x, y inzip(self.math_list, other.math_list)]
- return NumOperations(addlst)
- def__mul__(self, other):
- mullst = [x * y for x, y inzip(self.math_list, other.math_list)]
- return NumOperations(mullst)
- def__repr__(self):
- returnstr(self.math_list)
- x = NumOperations([100, 90, 80, 70, 60])
- y = NumOperations([10, 9, 8, 7, 6])
- p = x – y
- z = x + y
- q = x * y
- print(‘Subtraction: ‘+str(p))
- print(‘Addition: ‘+str(z))
- print(‘Multiplication: ‘+str(q))
Photo source: Unsplash
We can customize objects using Python operators such as plus, minus, and multiplication signs. This is a very powerful feature, and powerful because it makes it very easy to convey the ability to manipulate objects. Users don’t need to learn any new methods, they just add, subtract, or multiply NumOperations objects, and when the user prints the resulting object, they see the output they expect.
Isn’t that amazing?
Leave a comment like follow
We share the dry goods of AI learning and development. Welcome to pay attention to the “core reading technology” of AI vertical we-media on the whole platform.
(Add wechat: DXSXBB, join readers’ circle and discuss the freshest artificial intelligence technology.)