This is the last object-oriented part.
First look at two functions.
1.isinstance (obj, CLS)
Checks if obj is an object of class CLS
2.issubclass (Sub, super)
Check if the sub class is a derived class of super class
Class Bar:passclass Foo (bar): instance of passobj = foo () # Obj,bar (parent class of obj type and obj type) ret = isinstance (obj, Bar) print (ret) ret = Issubclass (Bar,foo) print (ret)------------------TrueFalse
3.super
By default, when a child class and a parent class have a method with the same name, the object of the subclass calls this method as a method of the called subclass. Super can force the invocation of the parent class's method.
For example
Class C1:def F1 (self): print (' C1.f1 ') return 123class C2 (C1): Def F1 (self): # The F1 method of actively executing the parent class ret = Super (c2,self). F1 () print (' C2.f1 ') return retobj = C2 () m=obj.f1 () print (m)-----------c1.f1c2.f1123
This approach allows us to flexibly extend existing classes and add new functionality without the need to modify existing code. Correspondingly, we need to modify the original code if we use the adorner.
For example, a super way to customize an ordered dictionary, the basic idea is to put the key in a list, because the list is ordered, so we take the value of the list to the key, and then through the key to the corresponding value, and finally re-splicing the output
Class mydict (dict): def __init__ (self): self.li = [] super (MyDict,self). __init__ ( ) def __setitem__ (Self, key, value): self.li.append (Key) super (MyDict,self). __setitem__ ( Key,value) def __str__ (self): temp_ list = [] for key in self.li: value = self.get (Key) temp_list.append ("'%s ':%s" % (Key,value,)) temp_str = "{" + ",". Join (Temp_list) + "}" &nbsP; return temp_str#obj = mydict () obj[' K1 '] = 123obj[' K2 '] = 456print (obj)
This article from "Mapo tofu" blog, declined reprint!
Python Learning Notes-Object-oriented (others)