Review 41 ~ 42 magic cube method in python

Magic cube method:

Structure and Deconstruction:

1: Constructor


When you inherit an immutable type and need to modify it, you can override it with this method
The main function is to return an instance object when an object is instantiated, which is usually the instantiated object of the parameter cls class. If so, other objects can also be returned.

>>> class Capstr(str):
	def __new__(cls,string):
		string = string.upper()
		return str.__new__(cls,string)

>>> a=Capstr('I love carrot')
>>> a

2: Destructor


This method will be called when the object is to be destroyed, and the garbage collection mechanism will not be enabled until all references to the generated object are del.

>>> class A:
	def __init__(self):
		print('I am__init_Method, I was called')
	def __del__(self):
		print('I am__del_Method, I was called')

>>> a1=A()
I am__init_Method, I was called
>>> a2=a1
>>> a3=a2
>>> del a2
>>> del a1
>>> del a3
 I am__del_Method, I was called

When the instance object needs to have explicit initialization steps, you can use the following methods

class Rectangle: 
	def __init__(self, x, y): 
		self.x = x 
		self.y = y
	def getPeri(self): 
		return (self.x + self.y) * 2 
	def getArea(self): 
		return self.x * self.y 
rect = Rectangle(3, 4)  

Attention_ init_ _ () the return value of the method must be None and cannot be anything else

>>> class Test:
	def __init__(self,x,y):
		return x+y

>>> t=Test(3,4)
Traceback (most recent call last):
  File "<pyshell#65>", line 1, in <module>
TypeError: __init__() should return None, not 'int'

Arithmetic operation:

Objects can be calculated

>>> a=int('123')
>>> b=int('456')
>>> c=float('345')
>>> a+b
>>> a+c

python's magic cube method can also customize the numerical processing of objects

add(self,other)Define the behavior of addition
sub(self,other)Define the behavior of subtraction
mul(self,other)Defines the behavior of multiplication
truediv(self,other)The act of defining true division
floordiv(self,other)Defines the behavior of integer division
mod(self,other)Define the behavior of the modulo algorithm
divmod(self,other)Defines the behavior when divmod() is called (a\b remainder)
pow(self,other)Defines the behavior when called by power() or * * operation
lshift(self,other)Defines the behavior of bitwise left shift
rshift(self,other)Defines the behavior of bitwise right shifting
and(other)Define the behavior of installation and operation&
xor(self,other)Define the behavior of bitwise XOR operations:^
or(self,other)Defines the behavior of bitwise or operations
>>> class New_int(int):
	def __add__(self,other):
		return int.__sub__(self,other)
	def __sub__(self,other):
		return int.__add__(self,other)

>>> a=New_int(3)
>>> b=New_int(5)
>>> a+b
>>> a-b
#+Return -, - return+

Here, an infinite recursive loop is entered, because self binds to A. when a+b is executed, return self+other is a+b again, and a+b keeps looping.

>>> class Try_int(int):
	def __add__(self,other):
		return self+other
	def __sub__(self,other):
		return self-other

>>> a=Try_int(3)
>>> b=Try_int(5)
>>> a+b
Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
  File "<pyshell#49>", line 3, in __add__
    return self+other
  File "<pyshell#49>", line 3, in __add__
    return self+other
  File "<pyshell#49>", line 3, in __add__
    return self+other
  [Previous line repeated 1022 more times]
RecursionError: maximum recursion depth exceeded

It can be improved as follows:

>>> class Try_int(int):
	def __add__(self,other):
		return int(self)+int(other)
	def __sub__(self,other):
		return int(self)-int(other)

>>> a=Try_int(3)
>>> b=Try_int(5)
>>> a+b
>>> a-b


1: Wrap the file object so that the file can be closed automatically when the object is deleted

>>> class Fileclose:
	def __init__(self,filename='D:\\carrot1.txt'):
	def __del__(self):
		del self.file

2: Define a class to realize the conversion from Celsius to Fahrenheit (Fahrenheit = Celsius * 1.8 + 32)

>>> class Cs(float):
	'Converting degrees Celsius to degrees Fahrenheit'
	def __new__(cls,arg):
		return float.__new__(cls,arg*1.8+32)
>>> cs=Cs(9)
>>> cs

3: Define a class that inherits from the int type and implements: when the incoming parameter is a string, return the sum of the ASCII codes of all characters of the changed string (use ord() to obtain the ASCII code value of a character).

>>> class A(int):
	def __new__(cls,arg):
		if isinstance(arg,str):
			for each in arg:
		return int.__new__(cls,arg)

>>> a=A('CARROT')
>>> a

4. The addition of two strings will automatically splice strings, and subtraction will throw an exception. Choose to define a class so that when A-B, all substrings with B will be taken from a.

>>> class A(str):
	def __sub__(self,other):
		return self.replace(other,'')

>>> a=A('I love carrothhhhhhf')
>>> b=A('hf')
>>> a-b
'I love carrothhhhh'
>>> c=A('h')
>>> a-c
'I love carrotf'
#a. The values of B and C remain unchanged

5. Define a class. When the addition, subtraction, multiplication and division operations occur between the instance objects of this class, the sum of ASCII codes of all strings of this object will be calculated.

class A:
    def __init__(self,arg):
        if isinstance(arg,str):
            for each in arg:

            print('Parameter input error')

    def __add__(self,other):
    def __sub__(self,other):
    def __mul__(self,other):
    def __truediv__(self,other):
    def __floordiv__(self,other):
>>> print(a1+a2)
>>> print(a1*a2)
>>> print(a1-a2)
>>> print(a1/a2)
>>> print(a1//a2)

6. Use shift operators

>>> class A(str):
	def __lshift__(self,other):
		return self[other:]+self[:other]
	def __rshift__(self,other):
		return self[-other:]+self[:-other]

>>> a=A('I love carrot')
>>> a<<3
'ove carrotI l'
>>> a>>3
'rotI love car'

Tags: Python

Posted by TheSaint97 on Tue, 19 Apr 2022 12:33:39 +0930