PHP前端开发

装饰器@staticmethod和@classmethod有什么区别

百变鹏仔 3个月前 (01-23) #Python
文章标签 有什么区别
装饰器@staticmethod和@classmethod的区别是:@staticmethod不需要self和cls参数,@classmethod不需要self参数,但需要cls参数。

通常来说,我们使用一个类的方法时,首先要实例化这个类,再用实例化的类来调用其方法

class Test(object):    """docstring for Test"""    def __init__(self, arg=None):        super(Test, self).__init__()        self.arg = arg    def say_hi(self):        print 'hello wrold'def main():    test = Test() //1. 首先实例化test类    test.say_hi() //2. 再调用类的方法if __name__ == '__main__':    main()

而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用。

这有利于组织代码,把某些应该属于某个类的函数给放到那个类里去,同时有利于命名空间的整洁。

class Test(object):    """docstring for Test"""    def __init__(self, arg=None):        super(Test, self).__init__()        self.arg = arg    def say_hi(self):        print 'hello wrold'    @staticmethod    def say_bad():        print 'say bad'    @classmethod    def say_good(cls):        print 'say good'def main():    test = Test()    test.say_hi()    Test.say_bad() //直接类名.方法名()来调用    Test.say_good() //直接类名.方法名()来调用if __name__ == '__main__':    main()

@staticmethod或@classmethod的区别

类的普通方法,地一个参数需要self参数表示自身。

@staticmethod不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。

@classmethod也不需要self参数,但第一个参数需要是表示自身类的cls参数。