400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

python内装饰器

一、内置装饰器

内置装饰器含义
classmethod 类方法
staticmethod 静态方法

二、普通方法(回顾)

# 1. 类的定义
class MethodClass:
    class_param= 0  # 类变量

    def __init__(self):  # 实列变量
        self.a = 'abc'

    def demo_method(self):
print('这是一个普通方法')

def demo_method2(self):
        self.demo_method()
        self.a= 'acb'
        print('这是一个普通方法')

# 定义类方法必须加 classmethod装饰器
    @classmethod
def class_method(cls):  # 类方法,第一个参数需要改为cls
        # cls.demo_method() 类方法内,不可以直接调用实列方法
        # cls.a  类方法内,不可以直接调用实列变量
        cls.class_method2()  # 类方法内,可以直接调用类变量与类方法
        print('这是一个类方法', cls.class_param)  # 类变量是可以直接调用的

    @classmethod
def class_method2(cls):  # 类方法,第一个参数需要改为cls
        print('这是一个类方法2', cls.class_param)


# 调用类方法
MethodClass.class_method()  # 无需实例化,直接通过 类.方法名 调用,也可以通过 实例.方法名 调用

# 实例化调用
demo = MethodClass()
demo.demo_method()# 在调用过程中,类和实列都可以直接调用类方法

# 调用普通方法,需要实例化,要不然会报错
# MethodClass.demo_method()

分享标题:python内装饰器
文章网址:http://mbwzsj.com/article/dsojdig.html

其他资讯

让你的专属顾问为你服务