执行父类的构造方法
实例:
class c1: def f1(self): print("c1.f1") class c2(c1): def f1(self): super(c2,self).f1() #主动执行父类的f1方法,另一种方法:c1.f1(self),3.0以后的版本尽量不用。 print("c2.f1") obj = c2() obj.f1()
通过继承的方式实现给原代码添加功能而不修改源代码:
1 class Foo: 2 def f1(self): 3 print("Foo.f1")
1 from settings import ClassName 2 from backend import commons 3 def execute(): 4 cls = getattr(commons, ClassName) #利用反射 5 obj = cls() 6 obj.f1() 7 8 if __name_ == "__main__": 9 execute() 10 11 12 ###########执行lib.py文件,需修改以下内容############ 13 from settings import ClassName 14 from settings import path 15 def execute(): 16 model = __import__(path, fromlist = True) 17 cls = getattr(model, ClassName) 18 obj = cls() 19 obj.f1 20 21 if __name_ == "__main__": 22 execute()
1 from backend.commons import Foo 2 3 4 class MyFoo(Foo): 5 def f1(self): 6 print("before") 7 super(MyFoo, self).f1() #执行原来的功能 8 print("after")
1 ClassName = "Foo" 2 3 4 ###########执行lib.py文件,需修改以下内容############# 5 path = "lib" 6 ClassName = "MyFoo"
实例:
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) + "}" obj = MyDict() obj["K1"] = 123 obj["k2"] = 456 print(obj)
设计模式之单例模式:(用来创建单个实例)
class Foo: instance = None def __init__(self): self.name = name @classmethod def get_instance(cls): #cls是类名 if cls.instance: return cls.instance else: obj = cls("alex") cls.instance = obj return obj obj1 =Foo.get_instance() print(obj1) obj2 = Foo.get_instance() print(obj2)