Double underline method in Python class

Source: Internet
Author: User

__getitem__,__setitem__ and __delitem__

  Implements a dictionary operation of object properties.

classPerson :def __init__(self, name, age, Hobby): Self.name=name Self.age=Age Self.hobby=Hobbydef __getitem__(self, item):ifhasattr (self, item):returnSelf.__dict__[item]def __setitem__(self, Key, value): Self.__dict__[Key] =valuedef __delitem__(self, key):delSelf.__dict__[Key]zxc= Person ('Zxc', 26,'Read')Print(Zxc.name)#zxc Object Native View Properties methodPrint(zxc['name'])#ZXC viewing methods implemented through GetItemzxc['name'] ='Zzy'  #implementing modifications with SetItemzxc['Weight'] = 70#increased by SetItem implementationPrint(ZXC.__dict__)#{' weight ': +, ' name ': ' Zzy ', ' hobby ': ' read ', ' Age ':delzxc['Hobby']#Delete with Delitem implementationPrint(ZXC.__dict__)#{' name ': ' Zzy ', ' weight ': +, ' age ': +}

__new__:    Construction Method: Create an Object

Instantiate to use the __new__ method

 class   Foo:  def  __init__   = name  def  __new__  (CLS, *args, * * kwargs):  return   '   Create an object  "  obj  = Foo ( "   ZXC   ") #   When instantiating an object, the __new__ method is called.  print  (obj) #   print: Create an object  

classFoo:def __init__(self, name): Self.name=namedef __new__(CLS, *args, * *Kwargs):returnObject.__new__(Foo)#the __new__ method inside object is used to construct objectsobj= Foo ('Zxc')Print(obj)#<__main__. Foo object at 0x000002cadd5c0048>

use of the __new__ method: Singleton mode

  A programming pattern: A class always has only one instance

classFoo:__instance=Falsedef __init__(self, Name, age): Self.name=name Self.age= Agedef __new__(CLS, *args, * *Kwargs):ifCls.__instance:#after instantiating an object, the subsequent instantiation uses the previous object            returnCls.__instanceCLS.__instance= object.__new__(CLS)returnCls.__instancea= Foo ('Zxc', 25) b= Foo ('ZXF', 22)Print(A.__dict__)#{' name ': ' Zxf ', ' Age ': $}Print(b.__dict__)#{' name ': ' Zxf ', ' Age ': $}B.hobby ='Read'Print(A.hobby)#Read#A and B are the same object

  __eq__ and __hash__

classFoo:def __init__(self, name): Self.name=Namea= Foo ('Zxc') b= Foo ('Zxc')Print(A = = b)#False normal A class of two objects even if the property is the same he's different.classFoo:def __init__(self, name): Self.name=namedef __eq__(self, Other):ifSelf.name = =Other.name:returnTrueElse:            returnFalsea= Foo ('Zxc') b= Foo ('Zxc')Print(a)#<__main__. Foo object at 0x000001543ba60048>Print(b)#<__main__. Foo object at 0x000001543ba604e0>Print(A = = b)#true A and B are not the same, but the result is true, which means that the __eq__ method is called when the = = comparison is used, and the default is to use the __eq__ method of the object.

class Foo:     def __hash__ (self):         return = Foo ()print(hash (a))  #  Ten   The built-in function hash is called the object's __hash__ method .

set will depend on __eq__ and __hash__

classFoo:def __init__(self, name, age, Sex): Self.name=name Self.age=Age Self.sex=Sexdef __hash__(self):returnHash (self.name+self.sex)def __eq__(self, Other):ifSelf.name = = Other.name andSelf.sex = =Other.sex:returnTrueElse:            returnFalsea= Foo ('Zxc', 25,'male') b= Foo ('Zxc', 24,'male')Print(Set ([A, b]))#{<__main__. Foo object at 0x000002bfb7fc04e0>}#when name and sex are the same, A and B are considered the same, set to go back#comment out the __hash__ method in the classPrint(Set ([A, b]))#error Display class Foo cannot hash description of the __hash__ method of a set dependent object#comment out the __eq__ method in the classPrint(Set ([A, b]))#The result is still two elements that do not go back to the __eq__ method of the set and rely on the object to return the result

  __len__

class Foo:     def __len__ (self):         return = Foo ()print(Len (a))  #  Ten   The built-in function Len calls the object's __len__ method, which is used by default as the __len__ method

Double underline method in Python class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.