面向对象之静态方法与类方法的区别

import time
class Date:
    def __init__(self,year,month,day):
        self.year=year
        self.month=month
        self.day=day
    @classmethod#哪个类来调用,就把这个类传入第一个参数cls,对象就是由此类产生的
    def now(cls):
        t=time.localtime()
        return cls(t.tm_year,t.tm_mon,t.tm_mday)
    @staticmethod#无论哪个类来调用,都是由父类产生的
    def now_sta():
        t=time.localtime()
        return Date(t.tm_year,t.tm_mon,t.tm_mday)


class EuroDate(Date):
    def __str__(self):
        return 'year: %s  month: %s  day: %s '%(self.year,self.month,self.day)

#
d1=EuroDate.now()#结果触发了__str__函数,说明这个对象是由类自己实例化的
print(d1)#year: 2018  month: 9  day: 9

d2=EuroDate.now_sta()#结果是父类实例化的对象,说明是父类实例化的对象
print(d2)#<__main__.Date object at 0x000001F5E191F0B8>

猜你喜欢

转载自www.cnblogs.com/happyfei/p/9613300.html