美文网首页
静态方法,类方法,和实例方法

静态方法,类方法,和实例方法

作者: 正在努力ing | 来源:发表于2018-08-04 10:31 被阅读0次
class Date:
    def __init__(self,year,month,day):
        self.year = year
        self.month = month
        self.day = day

    def __str__(self):
        return "{year}/{month}/{day}".format(year=self.year, month=self.month, day=self.day)

    @staticmethod
    def parse_str_st(list):
        year,month,day = tuple(list.split("-"))
        return Date(int(year),int(month),int(day))

    @classmethod
    def parse_str_cls(cls,list):
        year,month,day = tuple(list.split("."))
        return cls(int(year),int(month),int(day))

    #不需要返回类的静态方法,
    @staticmethod
    def show_month(month):
        if(month>6 and month<=12):
            return "ShangBanNian"
        else:
            return "XiaBanNian"

    #不需要返回类的类方法,但是还是需要传入类实例cls(是class的简写)
    @classmethod
    def show_am_pm(cls,hour):
        if hour>12:
            return "pm"
        else:
            return "am"
        
#用静态方法来解析
new_time_str = "2018-10-22"
new_time = Date.parse_str_st(new_time_str)
print(new_time)

#用类方法来解析字符
new_time_two = "2018.10.22"
new_time_tw = Date.parse_str_cls(new_time_two)
print(new_time_tw)

#用不用返回类的静态方法和类方法
res = Date.show_am_pm(10)
res2 = Date.show_month(12)
print(res)
print(res2)
2018/10/22
2018/10/22
am
ShangBanNian

利用静态方法把字符串变成整形,然后实例化,

注意:

不能先实例化,再去解析字符串。因为这样没有year,month,day这三个参数用来实例化,所以更加不可能调用实例方法来解析;此时就只能用静态方法
静态方法:
优点: 函数功能与实例解绑,获得这个功能不一定要实例化,此时更像是一种名称空间。
当然,我们也可以在类外面写这个函数,但是这样做就扩散了类代码的关系到类定义的外面,这样写就会导致以后代码维护的困难。
缺点:
每次都要返回类的名字来实例化

此时皆可以引入类方法:

类方法:

传入类的实例简写cls,返回cls的实例就行了
也可以纯做一个方法,不返回到类中间去,

相关文章

网友评论

      本文标题:静态方法,类方法,和实例方法

      本文链接:https://www.haomeiwen.com/subject/bsgpvftx.html