python - 在 python 2.7 中使用另一个类的装饰
问题描述
我正在尝试从 python 中的另一个类调用装饰器。下面是代码
file_1.py
class ABC:
def decorate_me(func):
def wrapper():
print "Hello I am in decorate_me func"
print "Calling decorator function"
func()
print "After decorator"
return wrapper
file_2.py
from file_1 import ABC
@ABC.decorate_me
def test():
print "In test function ."
test()
输出
TypeError: unbound method decorate_me() must be called with ABC instance as first argument (got function instance instead)
解决方案
正如错误所暗示的,您的装饰器是一种方法;尝试使其成为静态函数:
class ABC:
@staticmethod
def decorate_me(func):
...
但问题是你为什么把它放进去ABC
?
推荐阅读
- c++ - 为什么数组不打印第一个元素?
- c++ - abort() 已在项目中调用
- javascript - 在 Javascript 中遍历对象值
- asynchronous - 如何使用 Stream 和 Completer 在 dart 中下载文件
- salesforce - 在新选项卡/窗口中打开 VF 页面
- mongodb - MongoDB Compass 无法连接到服务器,但命令行有效
- python - Pandas 数据帧在尝试使用 read_csv 时出现解码错误
- laravel - 我需要从 laravel api 加载数据,并在颤动中分页
- mysql - 使用 MySQL 查询 JSON 数组
- python - 按两列分组时计算出现次数