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...
分类:
python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端