Dynamically add properties and methods to instances
Example :
from types import MethodType # For dynamically adding methods , introduce MethodType class cat(object): pass # Define an empty class cat1 = cat() cat1.name = "Tom" # Add properties dynamically print(cat1.name) def run(self): # Define a method first print(self.name+" Running ") cat.run = MethodType(run,cat1) # Dynamic add method cat1.run() # Calling method
Restrict dynamically adding attributes __slots__
class cat(object): __slots__=("name","age") # Restrict instance properties , Only attributes in parentheses can be added
operator overloading
Example :__add__
class Person(object): def __init__(self,num): self.num = num # Operator overloading def __add__(self, other): return Person(self.num + other.num) def __str__(self): return "num = "+str(self.num) per1 = Person(1) per2 = Person(2) print(per1+per2)
__lt__ :
# operator.lt(a, b) import operator # print(operator.lt(3, 2)) # The front number is less than the back number by Ture # print(operator.lt(1, 2)) # The front number is greater than the back number by False class Grade(object): def __init__(self,num): self.num = num #lt Operator overloading def __lt__(self, other): if self.num > other.num: # Colons must be different. Forget return 1 if self.num == other.num: return 0 if self.num < other.num: return 2 # def __str__(self): # return "num = "+str(self.num) # print(pow(2,2)) gra1 = Grade(2) gra2 = Grade(3) print(operator.lt(gra2, gra1)) # print(pow(gra1,2))
__pow__ # square
class Grade(object): def __init__(self,num): self.num = num #lt Operator overloading square def __pow__(self, power, modulo=None): return Grade(pow(self.num,power)) def __str__(self): return "num = "+str(self.num) # print(pow(2,2)) gra1 = Grade(2) # Define an object print(pow(gra1,2)) # Overloading of validation operators pow Explain :
https://blog.csdn.net/weixin_39712705/article/details/112315901
operator --- Standard operators replace functions :