python-面向对象-类的继承-单继承
1.继承是python面向对象的三大特性之一,是一种创建新类的方式,python中的继承,可以继承一个或者继承多个父类,新建的类被称之为派生类或者子类,被继承的类是父类,可以称之为基类,超类,继承是实现代码重用的重要方式。
#coding=utf-8; class father(object): #父类初始化方法 def __init__(self,id): self.id=id; #父类类方法 @classmethod def classmethod_father(cls,id,where): print(id,"father working...",where); #父类静态方法 @staticmethod def staticmethod_father(a,b,c): print(a,b,c,"father static method..."); #父类普通方法 def publicmethod_father(self,id,name): #id=self.id; #name=self.name; print("id:",id,"name:",name); class son(father): def __init__(self,sonid): super().__init__(id); self.sonid=sonid; @classmethod def classmethod_son(cls,sonid,sondo): print("调用者:",sonid,"son classmethod_son") @staticmethod def staticmethod_son(who): print("调用者:",who,"son static method ..."); def public_son(self,who): print("调用者:",who,"son public method..."); class grandson(son): def __init__(self,grandson_id): self.grandson_id=grandson_id; @classmethod def classmethod_grandson(cls,who): print("调用者",who,"grandson classmethod ..."); @staticmethod def staticgrandson(who): print("调用者","grandson staticmethod..."); def public_grandson(self,who): print("调用者",who,"grandson public..."); #设置一个变量 fathername="tom"; fatherid=123; #father实例化 f=father(fatherid); f.classmethod_father(fatherid,"北京"); f.staticmethod_father(111,222,333); f.publicmethod_father(fatherid,fathername); #father类调用 father.classmethod_father(888,"father类调用"); father.staticmethod_father("aaa","bbb","ccc"); father.publicmethod_father(1,100,"tom") #son实例调用 s = son(12345); s.classmethod_father(fatherid,"北京"); s.staticmethod_father(111,222,333); s.publicmethod_father(fatherid,fathername); s.classmethod_son(12345,"上海"); s.staticmethod_son("son") s.public_son("son"); #grandson实例调用 gs=grandson("1234578"); gs.classmethod_grandson("grandson"); gs.staticgrandson("grandson"); gs.public_grandson("grandson");
运行结果:
123 father working... 北京 111 222 333 father static method... id: 123 name: tom 888 father working... father类调用 aaa bbb ccc father static method... id: 100 name: tom 123 father working... 北京 111 222 333 father static method... id: 123 name: tom 调用者: 12345 son classmethod_son 调用者: son son static method ... 调用者: son son public method... 调用者 grandson grandson classmethod ... 调用者 grandson staticmethod... 调用者 grandson grandson public...