Python Learning note-day8 (Special method, Iter method, super method, ordered dictionary implementation, Python singleton mode)

Source: Internet
Author: User

Using a special method to implement a dictionary
#Use a class like dictionary dic[' xx ' with brackets in#Brief IntroductionclassFoo:#method called by the ① object [xx]    def __getitem__(self, item):return 'GetItem'    #② Object [XX] = method called by xxx    def __setitem__(self, Key, value):return 'SetItem'    #method called by the ③del object [xx]    def __delitem__(self, key):return 'Delitem'obj=Foo ()#①RET = obj['Test']#②obj['K1'] = 111#③delobj['K1']#ExampleclassFoo:def __getitem__(self, item):#Print (Type (item), item)        #Item.Start item.stop item.step        Print(Type (item))return123def __setitem__(self, Key, value):#Key.start key.stop key.step        Print(Type (key), type (value))def __delitem__(self, key):#Key.start key.stop key.step        Print(Type (key)) obj=Foo ()#incoming Shard, step, it will be a slice objectRET = Obj[1:4:2]Print(ret)
Iter method
# iter Method class Foo:     def __iter__ (self):         yield 1        yield 2= Foo ()#  When an object encounters an iteration (loop), the __iter__ method is accessed   for in obj:    print(item)
Super method
#Super Method: Actively executes the parent class methodclassC1:defF1 (self):Print('c1.f1')        return123classC2 (C1):defF1 (self):#F1 methods for actively executing parent classesRET =Super (C2, self). F1 ()Print('c2.f1')        returnRetobj=C2 () obj.f1 ( )
An ordered dictionary implementation
#ordered dictionary implementations (based on the Dict class)classmydict (dict):def __init__(self):#The list is ordered and an empty list is defined to accept the key valueSelf.li=[]        #__init__ methods for actively executing parent classesSuper (mydict, self).__init__()    def __setitem__(self, Key, value):#when we go to execute dic[' k1 ' = 123, the __setitem__ method is called        #before calling the Dict class, we add the key to the listself.li.append (Key)#__setitem__ methods for actively executing parent classesSuper (mydict, self).__setitem__(Key,value)def __str__(self):#Define aTemp_list = []         forKeyinchSelf.li:value=self.get (Key) Temp_list.append ("'%s ':%s"%(key,value)) Temp_list='{'+','. Join (Temp_list) +'}'        returnTemp_listobj=mydict () obj['K1'] = 123obj['K2'] = 456Print(obj)

= = "{' K1 ': 123, ' K2 ': 456}
Python single-instance mode
#Python Single-instance mode#1. Using the class method to implement#2. Using static fields to implementclassfoo:instance=Nonedef __init__(self,name): Self.name=name @classmethoddefget_instance (CLS):#CLS class name        ifCls.instance:#If the static field instance is True            returncls.instanceElse: obj= CLS ('Alex') Cls.instance= obj#            returnobjobj1=foo.get_instance ()Print(OBJ1)#here, the static field instance value of the class has been changedObj2 =foo.get_instance ()Print(OBJ2)#Obj1 is the same as OBJ2 memory address

Python Learning note-day8 (Special method, Iter method, super method, ordered dictionary implementation, Python singleton mode)

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.