面向对象编程——类方法和静态方法(八)

许多时候,我们创建了一个类,也定义了部分方法,如果我们想调用类中的方法,就必须创建一个对象,有时候显得非常的不方便。

python提供了classmethed(类方法)和staticmethed(静态方法)来解决这种情况。

普通方法绑定到对象,类方法绑定到类。

#使用一个方法一般要这样
class Classmethod_Demo():
    role = 'dog'

    def func(self):
        print('123')

c = Classmethod_Demo()     #创建一个对象
c.func()    

使用classmethed和staticmethed也能达到这种效果。

classmethod(类方法):不需要实例化,直接用类名调用就好,不用接受self参数,默认传cls,cls代表当前所在的类。

staticmethod(静态方法):完全可以当作普通函数去用,只不过这个函数通过类名.函数名调用。其它的和一般的函数没有区别。

普通对象方法至少需要一个self参数,代表类对象实例。

class Classmethod_Demo():
    role = 'dog'

    @classmethod       #类方法
    def func(cls):
        print("123")

Classmethod_Demo.func()

class staticmethod_Demo():
    role = "dog"

    @staticmethod      #静态方法
    def func():
        print("123")
staticmethod_Demo.func()
原文地址:https://www.cnblogs.com/yangmingxianshen/p/7880198.html