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

    python静态方法的用法

    小妮浅浅小妮浅浅2021-10-19 10:38:25原创7098

    1、通过装饰器@staticmethod定义静态方法。

    2、@staticmethod必须写在方法上。

    3、在静态方法中访问实例属性和实例方法会导致错误。

    4、调用格式:“类名.静态方法名(参数列表)”

    实例

    class Person:
     
        # 类属性
        school = "中加枫华国际学校"
        tuition = 100000
        count = 0
     
        # 实例属性
        def __init__(self,name,age):
            self.name = name
            self.age = age
            Person.count = Person.count+1
     
        # 静态实例
        @staticmethod
        def addNum(a,b):
          print("{0}+{1}={2}".format(a,b,a+b))
          return a+b
     
        # 实例方法
        def get_score(self):
            print("姓名:{0};年龄:{1}".format(self.name,self.age))
     
    stu1 = Person("sue", 22)
    stu1.get_score()
    Person.addNum(1,2)

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

    专题推荐:python 静态方法
    品易云
    上一篇:python类方法的注意点 下一篇:python中__del__方法的使用

    相关文章推荐

    • python TKinter弹出式菜单的使用• python canvas画布的介绍• python中sys.argv模块的介绍• python中getopt模块是什么• python中argparse库是什么• python如何委派生成器• python闭包的特点• python中AttributeError异常的介绍• python列表访问的方法• python生成器推导式是什么• python字典添加值的方法• python序列解包的使用• python模块的name属性• python实例方法的使用注意• python类方法的注意点

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网