Python基础学习:装饰器的学习,以及classmethod和staticmethod两种装饰器简单用法

Python基础学习:装饰器的学习,以及classmethod和staticmethod两种装饰器简单用法

1、staticmethod 是类静态方法
2、classmethod 所接收的第一个参数不是 self ,而是cls
3、被这两种装饰器装饰的方法不需要实例化即可以调用

'''
    这篇主要讲装饰器
'''
import time


def func(f):
    def wrapper():
        i = 0
        while i < 10:
            f()
            time.sleep(1)
            i += 1
            print(i)
    return wrapper


@func
def f():
    print('hello')

a = f()


# staticmethod装饰器用法,调用可以不需要实例化
# 该类其他方法前没有staticmethod装饰器,仍然需要进行实例化
class decorator(object):

    def print_two(self):
        print('hello, two')

    @staticmethod
    def print_hello():
        print('hello world')

    def print_one(self):
        print('hello, one')

# 调用staticmethod装饰的decorator的方法
d = decorator.print_hello()

# 直接调用无staticmethod装饰的decorator的方法
# decorator.print_one()
'''
Traceback (most recent call last):
  File "D:/test/PycharmProjects/untitled/test/decorator.py", line 46, in <module>
    decorator.print_one()
TypeError: print_one() missing 1 required positional argument: 'self'
'''
# 实例化无staticmethod装饰的decorator的方法
decorator().print_two()
'''
    hello, two
'''
class decorator_two(object):
    def print_hello(self):
        print('hello world')

# 不实例化调用
# d_two = decorator_two.print_hello()
'''报错
    Traceback (most recent call last):
  File "D:/test/PycharmProjects/untitled/test/decorator.py", line 47, in <module>
    d_two = decorator_two.print_hello()
TypeError: print_hello() missing 1 required positional argument: 'self'
'''


# 实例化调用
d_three = decorator_two().print_hello()

class cls_one(object):
    a = 3 # 局部变量

    def __init__(self):
        self.c = 1 # 全局变量
        b = 2 # 局部变量

    def sum_one(self):
        sum_o = 1 + 2 + self.c
        return sum_o

    @classmethod
    def sum_two(cls):
        '''
            需要在方法里面对cls进行实例化
        :return:
        '''
        print('hello')
        print(cls().a)
        print(cls.a)
        print(cls().c)
        print(cls().sum_one())


# 调用classmethod里的方法不需要进行实例化
A = cls_one
A.sum_two()

# 调用类里面没有classmethod装饰的方法需要进行实例化
# A.sum_one()
'''
Traceback (most recent call last):
  File "D:/test/PycharmProjects/untitled/test/decorator.py", line 86, in <module>
    A.sum_one()
TypeError: sum_one() missing 1 required positional argument: 'self'
'''
A().sum_one()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值