Advanced Object-Oriented (item series, __ new __, __ hash __, __ eq__)

 

 

 

Advanced Object-Oriented (item series, __ new __, __ hash __, __ eq__)

 

A, item series

 

getitem, setitem, delitem (results achieved during the operation is actually CRUD)

 

class Foo:
     DEF  the __init__ (Self, name, Age, Sex): 
        the self.name = name 
        self.age = Age 
        self.sex = Sex 

    DEF  the __getitem__ (Self, Item):   # and f [ 'xx'] corresponding to form 
        IF the hasattr (Self, Item):
             return . Self the __dict__ [Item] 

    DEF  the __setitem__ (Self, Key, value):   # and f [ 'xx'] = ' ss' form corresponding to 
        Self. the __dict__ [Key] = value 

    DEF  __delitem__ is (Self, Key):   #And del f [ 'xx'] corresponding to form 
        del Self. The __dict__ [Key] 

F = Foo ( ' Egon ' , 30, ' M ' )
 Print (F [ ' name ' ])
 #   F [ 'name'] --- object [ 'xx'] this form will trigger __getitem__ foregoing method, the name passed to Item 
#   supported in such a manner that the properties of the object name acquired, taken normal to the attribute is f.name 

F [ ' Hobby ' ] = ' M ' 
# newly added value and key, triggering __setitem__ method, and the corresponding property values into the original dictionary 
Print (F [ ' Hobby ' ], f.hobby)
 #In f [ 'hobby'] in such a way to take the new property, the original normal value f.hobby 

# del f.hobby # remove normal manner 
# Print (f.hobby) # At this time being given, show: AttributeError : 'Foo' Object attribute has nO 'Hobby' 

del f [ ' Hobby ' ]
 # If you perform this step to, will be displayed: AttributeError: __delitem__, this method shows no 
# this way you delete trigger __delitem__ method, in front of class which would have to have a definition of that method 
Print (f. __dict__ )   # dictionary there is no attribute of a hobby

operation result:

C: \ Users \ 3-2 \ PycharmProjects \ untitled \ venv \ Scripts \ python.exe C: / Users / 3-2 / PycharmProjects / untitled / object oriented Advanced .py 
Egon 
M M 
{ ' Sex ' : ' M ' , ' Age ' : 30, ' name ' : ' Egon ' } 

Process Finished Exit with code 0

 

This can be directly used in brackets tone, for example on the implementation process dictionaries, lists, and inside there is a reason for that item series this mechanism
This can be directly used in brackets tone, for example on the implementation process dictionaries, lists, and inside there is a reason for that item series this mechanism 
object native support __delattr__ so it can be without being given directly del f.hobby, but del f [ 'hobby'] obtained through their realization, 
so when there is no class method will be given when __delitem__

 

Two, __ new__
__init__: initialization method 
__new__: constructor, create an object. __new__ self is constructed, i.e. __new__ method is self generated mechanism 
usually is no need to use the method of performing __new__, the following examples are briefly described how to use it:
class A:
     DEF  the __init__ (Self): 
        self.x =. 1
         Print ( ' in the init function ' )
     DEF  __new__ (cls, * args, ** kwargs):
         # pass a default parameter cls, before executing further __new__ no self, we can only transfer an incoming class 
        Print ( ' in new new function ' )
         return Object. __new__ (a, * args, ** kwargs)
         # Object .__ new__ create a new object, then the object will pass self position, so that when performing the self can use the objects 

a = a ()   # instantiated, will first perform __new__ method, and then performing the method __init__

operation result:

in new function
in init function

Process finished with exit code 0
A typical design pattern (23 kinds): Singleton Pattern
 Singleton pattern: a class is always only one instance; when the first instance of this class when it creates an instance of the object; Once again instantiation, 
objects will use previously created

 

Example # achieve Singleton pattern: 

class A: __instance = False # private static variable does not want others to use, have to go through their own set DEF __init__ (Self, name, Age): self.name = name self.age = Age DEF __new__ (CLS, * args, ** kwargs): IF CLS. __instance : # If true then execute the code below, otherwise the code behind # second came in on a line with the return CLS. __instance # first the second coming directly to objects created before the return to self CLS. __instance = Object. __new__ (a) #The first came in because that is __instance = False, so the implementation of this line of code # use object .__ new__ create a new object of a class A, and assigned to the instance .__ CLS return CLS. __Instance # Here is the new Object return back to Egon = a ( ' Egg ' , 38 ) # really instantiate the object and the memory for the object it is inside the self, but the object here is to always use object .__ new__ created, # because they have a target , would not have to use the object inside the # reasons anyway possible to use a single embodiment of the method __new__ egon.cloth = ' florets jacket ' Nezha = a ( ' Nazha ' , 25 ) nezha.shoes = ' small white shoes ' Print (Nezha) Print (Egon) # execute here based on operating results display memory address is the same, that is to say the second time is instantiated in after the first instance of the # object operation, but did not create another again the object representing a memory, if the second instance of the same transmission parameters and the original object, # parameter values will be overwritten if a second example of the transfer part of the original parameters only attribute, then the same cover, the original continue to be # in the performance of an existing object in Print (nezha.name) Print (egon.name) # execute here egon original name has been covered nezha Print (nezha.cloth) # execute here the original egon of cloth will continue to wear on nezha

operation result:

<__main__.A object at 0x0000025C0C2293C8>
<__main__.A object at 0x0000025C0C2293C8>
nazha
nazha
小花袄

 

 

Three, __ hash__

# In the absence of defined __hash__ method, hash are directed at memory address, rather than for a different object attributes, memory addresses, hash results are not the same 

class A:
  DEF __init__ (Self, name, Sex):
    Self .name
= name
A
= A ( ' EGN ' , ' M ' )
B
= A ( ' Egon ' , ' NV ' )
Print (the hash (A))
Print (the hash (B))

operation result:

154259419512
154259419617

 

# After defining -__ hash__ method, different hash values will be different attributes, the same hash value of the same property also:
 class A:
     DEF  the __init__ (Self, name, Sex): 
        the self.name = name 
        self.sex = Sex
     DEF  a __hash__ (Self):
         return the hash (the self.name + self.sex) 

A = A ( ' Egon ' , ' M ' ) 
B = A ( ' Egon ' , ' M ' ) 
C = A ( ' Egon ' , 'nv')
print(hash(a))
print(hash(b))
print(hash(c))

operation result:

8385798543724353936
8385798543724353936
-7270162062837990016

 

Four, __ eq__

 

When no __eq__ method, both memory address comparison is Comparison:
 class A:
     DEF  the __init__ (Self, name): 
        the self.name = name 

OBJ1 = A ( ' Egg ' ) 
obj2 = A ( ' Egg ' )
 Print ( == obj1 obj2)
 # no definition __eq__ method when the default comparison when comparing the memory address, the top two memory addresses are not the same

operation result:

False

 

# __Eq__ setting can define their own method of performing a content, '==' triggered _eq_ Method 
class A: 
    DEF the __init __ (Self, name): 
        the self.name = name 

    DEF __eq __ (Self, OTHER): 
        IF Self == other.name .name: 
            return True 
        the else: 
            return False 

OBJ1 = a ( 'Egg') 
obj2 = a ( 'Egg') 
OBJ3 = a ( 'an EGG') 
Print (OBJ1 == obj2) equals triggered # __eq__ 
Print (obj2 == obj3) # equals triggered __eq__

 

operation result:

True
False

Process finished with exit code 0

Guess you like

Origin www.cnblogs.com/wxm422562/p/12031164.html