一、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类和对象中的知识,构建自己的程序。