python - 在父类方法上使用子类中指定的装饰器
问题描述
假设我有两个类Child
和Parent
(这是 的基类Child
)。我有另一个类Dec
,它包含一个dec
我想在Parent
方法上使用的装饰器。我希望能够指定一个Dec
应该在Child
.
这是我到目前为止所尝试的:
class Dec():
def dec(self, func):
def wrapper(self):
print("Before func call")
func(self)
print("After func call")
return wrapper
class Parent():
dec = None
@dec.dec
def p(self):
print('hello')
dec = Dec()
class Child(Parent):
a = dec
t = Child()
t.p()
所以,我得到了
AttributeError: 'NoneType' object has no attribute 'dec'
在@dec.dec
.
是否有任何选项可以指定一个应该在课堂上使用的带有装饰器的Child
类?
解决方案
您在这里遇到的问题与范围界定有关。
当我运行这段代码时,我收到了这个错误:
...<stack trace>...
File ".\__main__.py", line 10, in <module>
class Parent():
File ".\__main__.py", line 13, in Parent
@dec.dec
AttributeError: 'NoneType' object has no attribute 'dec'
使用它,您可以看到您有一些范围问题。在此文件中,您定义dec
了多次。不要像第 11 行那样实例化,而是Dec
定义Dec.dec(...)
为 a @classmethod
,可从类本身调用,而不仅仅是类的实例。
这是一个潜在的解决方案:
class Dec():
@classmethod
def dec(self, func):
def wrapper(self):
print("Before func call")
func(self)
print("After func call")
return wrapper
class Parent():
@Dec.dec
def p(self):
print('hello')
class Child(Parent):
pass # you didn't really need anything here.
t = Child()
t.p()
这提供了我认为是预期的行为:
Before func call
hello
After func call
推荐阅读
- python - TypeError:使用 Pyinstaller 转换 .py 时预期的 str、bytes 或 os.PathLike 对象,而不是 WindowsPath
- testing - Quarkus / Keycloak - 如何在测试中模拟 Keycloak 服务器
- amazon-ec2 - 从端口 443 到 8443 的重定向不能从外部用于独立的 tomcat
- sql - 为什么我不能同时使用 ORDER BY 和 GROUP BY
- knockout.js - 不能多次对同一个元素应用绑定,淘汰js问题
- sql - CASE WHEN 子句的非 case 条件中的 SQL 错误
- node.js - 警告:使用 Angular 和 ng2-pdf-viewer 渲染 PDF 文档时索引所有 PDF 对象
- javascript - 如何获取在jQuery中单击相应按钮的表中一行的记录
- julia - 在 Julia 中读取大型 CSV 文件所花费的时间
- c++ - GetWindowLong(hwnd, 0) 是什么意思?