静态方法与类方法理解与区别、调用关系

静态方法实际上就是普通函数,定义形式是在def行前加修饰符@staticmethod,只是由于某种原因需要定义在类里面。静态方法的参数可以根据需要定义,不需要特殊的self参数。可以通过类名或者值为实例对象的变量,已属性引用的方式调用静态方法

类方法定义形式是在def行前加修饰符@classmethod,这种方法必须有一个表示其调用类的参数,一般用cls作为参数名,还可以有任意多个其他参数。类方法也是类对象的属性,可以以属性访问的形式调用。在类方法执行时,调用它的类将自动约束到方法的cls参数,可以通过这个参数访问该类的其他属性。通常用类方法实现与本类的所有对象有关的操作。

class Apple:

    def fun1(self):
        return 'normal'

    @staticmethod
    def fun2():

        return 'staticmethod'

    @classmethod
    def fun3(cls):

        return 'classmethod'


print(Apple.fun1)
print(Apple.fun2)
print(Apple.fun3)

print('-'*80)

apple = Apple()
print(apple.fun1)
print(apple.fun2)
print(apple.fun3)

print("-"*80)

apple1 = Apple()
print(apple1.fun1)
print(apple1.fun2)
print(apple1.fun3)
print(Apple.fun1(apple))
print(Apple.fun1(Apple))

结果如下:

<function Apple.fun1 at 0x0000000002944598>
<function Apple.fun2 at 0x0000000002944620>
<bound method Apple.fun3 of <class '__main__.Apple'>>
--------------------------------------------------------------------------------
<bound method Apple.fun1 of <__main__.Apple object at 0x000000000294A668>>
<function Apple.fun2 at 0x0000000002944620>
<bound method Apple.fun3 of <class '__main__.Apple'>>
--------------------------------------------------------------------------------
<bound method Apple.fun1 of <__main__.Apple object at 0x000000000294A6D8>>
<function Apple.fun2 at 0x0000000002944620>
<bound method Apple.fun3 of <class '__main__.Apple'>>
normal
normal

对比结果1,5,9行
实例方法fun1通过类调用时,它是函数,而实例化apple和apple1之后,它属于绑定的方法,且实例化后的apple和apple1内存地址不同,因为它们属于不同的实例对象。


对比结果2,6,10行
静态方法fun2通过类调用或者通过实例化后的对象调用,是没有任何区别的,全部都是指向同一块内存地址。可以简单的理解成静态方法与类或者实例没有任何关系,一旦调用后,它的内存地址即确定。


对比结果3,7,11行
类方法fun3通过类调用或者通过实例化后的对象调用,是没有任何区别的,全部都是指向同一块内存地址。为什么?因为实例化对象apple和apple1调用类方法fun3传入的第一个参数是类本身Apple,也就是说apple.fun3 = apple1.fun3 = Apple.fun3。

  1. 静态方法装饰器下定义的方法属于函数(function);
  2. 类方法装饰器下定义的方法属于方法(method);
  3. 静态方法无需传入任何参数;
  4. 类方法传入的第一个参数必须是class本身cls;
  5. 静态方法与类方法一旦被调用,内存地址即确定。通过类调用和通过实例化对象调用的结果完全一样。
  6. 静态方法是无妨访问实例变量和类变量的,类成员方法无法访问实例变量但是可以访问类变量
  7. 类和实例都可以访问静态方法、实例方法,类方法,但在类访问实例方法时,可以传类也可以传实例。

猜你喜欢

转载自blog.csdn.net/Lq_520/article/details/81701759