静态方法无绑定,和普通函数使用方法一样,只是需要通过类或者实例来调用。没有隐性参数。
实例方法针对的是实例,类方法针对的是类,他们都可以继承和重新定义,而静态方法则不能继承,可以认为是全局函数。
#https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods class Date: def __init__(self,month,day,year): self.month = month self.day = day self.year = year def display(self): return "parent class {0}-{1}-{2}".format(self.month,self.day,self.year) @staticmethod def smil(month,day): return Date(month,day,2015) @classmethod def cmil(self,month,day): return self(month,day,2015) class DateSub(Date): def display(self): return "subclass {0}-{1}-{2}".format(self.month,self.day,self.year) new_year = Date(1,1,2016) mi_new_year = Date.smil(1,2) print(new_year.display()) print(mi_new_year.display()) print(isinstance(new_year,Date)) print(isinstance(mi_new_year,Date)) print("-"*40) dateSub1=DateSub(10,19,2017) dateSub2 =DateSub.smil(10,10) dateSub3 =DateSub.cmil(10,11) print(dateSub1.display()) print(dateSub2.display()) print(dateSub3.display()) print("isinstance(dateSub1,DateSub) = %s " % isinstance(dateSub1,DateSub)) print("isinstance(dateSub2,DateSub) = %s " % isinstance(dateSub2,DateSub)) #subclass create plain Date object print("isinstance(dateSub2,Date) = %s " % isinstance(dateSub2,Date)) print("isinstance(dateSub3,DateSub) = %s " % isinstance(dateSub3,DateSub)) print("-"*40) print Date.display print Date.smil print Date.cmil print Date.cmil(1,1)