python静态方法的使用注意点

405次阅读
没有评论

python静态方法的使用注意点

使用说明

1、静态方法取消了不需要的参数传递,能够减少不必要的内存占用和性能消耗。

2、类中定义了同名的静态方法时,调用方法会优先执行最后定义的方法。

实例

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)
 
    def yesterday(Date):
        Date.day -= 1
 
    @staticmethod       #  用这个装饰器表明是静态方法,这个要注意。
    def static(date_str):
        year, month, day = tuple(date_str.split("-"))
        return Date(int(year), int(month), int(day))
 
 
new_day=Date.static("2018-10-10")    #由于静态方法不属于实例 所以调用的时候, 用类名.静态方法,这个要注意
print(new_day)
 
 
#打印结果  正好是咱们的预期结果。
2018-10-10
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2022-04-14发表,共计660字。
新手QQ群:570568346,欢迎进群讨论 Python51学习