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()