python 中super方法、静态方法、类方法
一、python中的super方法
先上代码看个简单例子
1 class A: 2 def __init__(self): 3 print('AA __init__') 4 5 class B(A): 6 def __init__(self): 7 print("BB __init__") 8 9 class C(A): 10 pass 11 12 class D(C, B): 13 def __init__(self): 14 print ('DD __init__') 15 super().__init__() # python3 中直接可以这样写, super中不传参 16 17 d = D()
结果输出:
DD __init__ BB __init__
我们来看一下子类D的继承顺序:
>>> print (D.__mro__) (<class '__main__.D'>, <class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
结论:super方法并不是我们所认为的那样,执行父类的方法,而是根据python中继承顺序的算法向前找的。
二、静态方法、类方法
类中的静态方法和类方法的定义方法分别用装饰器 @staticmethod 和 @classmethod 来定义,你可以将静态方法和类方法当成我们在程序中写的普通函数,它们和普通 def 函数不同之处在于:
1:静态方法和类方法创建时是初始在类的名称空间当中的;
2:静态方法和类方法的调用必须使用 类.方法名 的方式
那么这两个类中的方法有什么用呢?其实你只要遵循python的语法语义,按照它的协议来,想怎么用全看你自己对python使用的灵活性,只要不违规就好。这里发个关于静态方法和类方法的例子:
1 class Date: 2 def __init__(self, year, month, day): 3 self.year = year 4 self.month = month 5 self.day = day 6 def __str__(self): 7 return "Today is {year}/{month}/{day}.".format(year=self.year, month=self.month, day=self.day) 8 9 @staticmethod 10 def check_date_string(my_string): 11 year, month, day = my_string.split("-") 12 if int(year) > 0 and (int(month) > 0 and int(month) <= 12) and (int(day) > 0 and int(day) <= 31): 13 return True 14 return False 15 16 @classmethod 17 def format_date_string(cls, my_string): 18 year, month, day = my_string.split("-") 19 return cls(year, month, day) 20 21 dt = Date('2019', '1', '20') 22 print(dt) 23 print ("*"*10) 24 25 str1 = "2019-18-9" # 月份写错 26 print(Date.check_date_string(str1)) 27 print ("*"*10) 28 29 str2 = "2019-11-22" 30 print(Date.check_date_string(str2)) 31 print(Date.format_date_string(str2)) # 类方法,返回一个Date对象,print时打印 __str__
代码当然不严谨,不过只是写个简单例子旨在说明静态方法和类方法的一种应用场景,输出如下:
Today is 2019/1/20. ********** False ********** True Today is 2019/11/22.
真正写代码时要视实际需求,来灵活使用python类和对象中的知识,构建自己的程序。
分类:
python之路
标签:
python 元编程
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通