Python基础——@staticmethod与@classmethod

来源:互联网 发布:丹朱围棋软件 编辑:程序博客网 时间:2024/06/06 02:17
  • @staticmethod与隐式的静态成员方法的区别在于是否允许实例对象调用该静态方法(后者是不允许的)

  • @staticmethod与@classmethod的区别在于后者无论是被实例调用还是被类对象调用传递进来的第一个参数永远是类对象(class object)

@staticmethod的用法

使用@staticmethod声明的成员函数具有C++类的静态成员函数的相同的用法,既可以被对象调用,更可以被类本身调用,因为静态成员函数属于类本身。
在python类的定义中,在成员函数的参数列表中如果不指定第一个参数为self(也即c++中的this指针),标识着该方法属于类的方法,但与@staticmethod的不同之处在于,不可被对象调用。

class Dog(object):    count = 0    dogs = []    def __init__(self, name):        self.name = name        Dog.count += 1        Dog.dogs.append(name)    def bar(self, n):        print('{} says {}'.format(self.name, 'bar'*n))    def rollCall(n): # this is a implicitly a class method         print('There are {} dog.'.format(Dog.count))        if n >= Dog.count or n < 0:            print('They are :')            for dog in Dog.dogs:                print(' {}'.format(dog))        else:            print('The dog indexed {} is {}'.format(n, Dog.dogs[n]))if __name__ == '__main__':    fido = Dog('Fido')    Dog.rollCall(0)         # 正确    fido.rollCall(0)        # 抛异常   

如果将rollCall()声明为@staticmethod,使用实例对象也可调用该方法。

@staticmethod与@classmethod的差异

注意区别类对象(class object)实例对象(instance object)

class Kls(object):    no_inst = 0    def __init__(self):        Kls.no_inst += 1    @classmethod    def get_no_of_instance(cls_obj):        return cls_obj.no_instik1 = Kls()ik2 = Kls()print(ik1.get_no_of_instance())         # 2print(Kls.get_no_of_instance())         # 2

使用@classmethod成员函数的一大优势在于,无论是通过实例对象(instance object,如ik1)还是通过类对象(class object,如Kls)调用该类型方法时,传递进来的第一个参数总是该类对象(也就是将Kls传递给cls_obj)。

0 0