Object oriented — special members

1.The call of a special member of a class

 1 class SpecialMembers:
 2     #Class construction method
 3     def __init__(self):
 4         print("A method is constructed.")
 5     
 6     def __call__(self):
 7         print("An object is constructed.")
 8 
 9 #Create an object and execute the class construction method.
10 obj = SpecialMembers()
11 #Construction method of execution objects
12 obj()
13 #First execute the class construction method, then execute the object construction method.
14 SpecialMembers()()

2.Getitem, setitem, delitem of special members of a class

 1 class SpecialMembers:
 2     #When obj ['value'] is executed, the u getitem_uuuuuuuuuuuuuuuuuu
 3     def __getitem__(self,item):
 4         print(item)
 5     def __setitem__(self,key,value):
 6         print(key,value)
 7     def __delitem__(self,key):
 8         print(key)
 9 
10 #Create an object
11 obj = SpecialMembers()
12 #Automatic execution of __getitem__ method
13 obj['value']
14 #Automatic execution of __setitem__ method
15 obj['k1'] = 'values'
16 #Automatic execution of __delitem__ method
17 del obj['key']

3.The dict of a special member of a class

Gets all members of a class or object

 1 class SpecialMembers:
 2     """
 3     Class Comments 4     """
 5     def __init__(self,name,age):
 6         self.name = 'abc'
 7         self.age = 18
 8 #Get members from a class
 9 print(SpecialMembers.__dict__)
10 #Create an object
11 obj = SpecialMembers()
12 #Get members from objects
13 print(obj.__dict__)#Output in the form of dictionaries

4.The ITER of a special member of a class

 1 class SpecialMembers:
 2     def __iter__(self):
 3         yield 1
 4         yield 2
 5         yield 3
 6 #Create an object
 7 obj = SpecialMembers()
 8 #If the for loop object is executed, the object's u iter_u method is automatically executed, and u iter_u is a generator
 9 for i in obj:
10     print(i)

5.The add of a special member of a class

 1 class SpecialMembers:
 2     def __init__(self,a1,a2):
 3         self.a1 = a1
 4         self.a2 = a2
 5     def __add__(self,other):
 6         return self.a1 + other.a2
 7 
 8 obj1 = SpecialMembers(1,2)
 9 obj2 = SpecialMembers(3,4)
10 print(obj1 + obj2)#5

6.The real construction method

 1 class Foo:
 2     def __init__(self,a1,a2):#Initialization method
 3         """
 4         Initializing data for empty objects 5         """
 6         self.a1 = a1
 7         self.s2 = a2
 8 
 9     def __new__(cls,*args,**kwargs):
10         """
11         Create an empty object12         """
13         return object.__new__(cls)#pythonCreate an object of the current class internally.
14 
15 obj = Foo(1,2)
16 print(obj)

 

Leave a Reply

Your email address will not be published. Required fields are marked *