python静态方法-类方法

关于类的静态方法:@staticmethod 和 @classmethod 

1、使用这两种方法,不用实例化类,直接可以用,如:Stu.say()

2、两种方法的区别:

  1、@staticmethod 不需要加参数;

      调用类变量用:类名.类变量名;

      调用类函数用:类名.函数()

  2、@classmethod 需要加参数cls;

      调用类变量用:cls.类变量名;

      调用类函数用:cls().函数()

class Stu(object):
    country = 'china'  # 类变量
    def __init__(self, name='world'):
        self.name = name

    @staticmethod
    # 静态方法,和类本身没有什么关系了,就相当于在类里面定义了一个方法而已
    def say():
        print('shanghai')
        print(Stu.country)
        Stu('static').hi()

    @classmethod
    # 静态方法,和类方法不同的是,它可以使用类变量,必须要传一个值,代表的就是这个类
    def hello(cls):
        print('-------------------------')
        print(cls.country)
        cls.say()
        cls().hi()

    def hi(self):
        # 这个是实例方法
        print(self.name)

Stu.say()
Stu.hello()

# t = Stu('name')
# t.hi()
# t.say()
# t.hello()
原文地址:https://www.cnblogs.com/eeoo/p/7459502.html