• 技术文章 >Python技术 >Python基础教程

    python静态方法的使用注意点

    小妮浅浅小妮浅浅2021-08-20 09:11:59原创2417

    使用说明

    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

    以上就是python静态方法的使用注意点,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python静态方法
    品易云
    上一篇:python类方法的使用注意 下一篇:python访问元组的两种方法

    相关文章推荐

    • python pprint.pformat()函数的使用• python else在循环语句执行的情况• python coroutine的运行过程• python如何输入数据类型检查• python异常的捕捉和补救• python三种流程控制的语句• python析构函数的常见应用• python析构函数的底层机制• python析构函数的使用注意• python中类对象的介绍• python类属性的概念• python类属性的内存分析• python类方法的使用注意

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网