|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
想问一下为什么下面第一种情况是OK的,第二种就会报错呢
第一种
- class Logging:
- def __init__(self, func):
- self.func = func
- def __call__(self):
- print(f"{self.func.__name__}()")
- self.func()
-
- @Logging
- def say():
- print("hello")
-
- say()
复制代码
第二种
- class Logging:
- def __init__(self, func, level="INFO"):
- self.func = func
- self.level = level
- def __call__(self):
- print(f"[{self.level}: {self.func}()]")
- self.func()
-
- @Logging(level="ERROR")
- def say():
- print("hello")
- say()
复制代码
- Traceback (most recent call last):
- File "C:\Users\JiJing\Desktop\test.py", line 10, in <module>
- @Logging(level="ERROR")
- TypeError: Logging.__init__() missing 1 required positional argument: 'func'
复制代码
在初始化的时候,应该 Logging(func, level) 这样传参,但是因为装饰器的语法原因,你原来的那个 - @Logging(level="ERROR")
- def say():
- print("hello")
复制代码这个函数的定义被 Python 解析成了
- def say():
- print("hello")
- say = Logging(level = 'ERROR')(say)
复制代码此时 Python 就会报错。
|
|