举个例子:
class Foo:
def wrapper(func):
def wrapped(self):
try:
return func(self)
except Exception:
raise
finally:
print('Some error in wrapped function')
return wrapped
@wrapper
def division(self, x, y):
return x / y
class Bar(Foo):
@wrapper
def multiplication(self, x, y):
return x * y
f = Foo()
print(f.division(5, 2))
b = Bar()
print(b.multiplication(3, 3))
错误:
Traceback (most recent call last):
File "d:\Dev\abc-python\count.py", line 18, in <module>
class Bar(Foo):
File "d:\Dev\abc-python\count.py", line 20, in Bar
@wrapper
NameError: name 'wrapper' is not defined
继承时,我期望子类拥有父类的所有方法,我没有找到相反的信息,至少我看不出为什么wrapper
不被父类继承 child 类。
是的,我可以将装饰器移动到一个单独的文件中并导入它们,也许它会“更正确”,但我想了解为什么它们不被继承。
最佳答案
这些名称都不在类 block 的范围内。它们是父类命名空间的成员,因此可以在 Foo.wrapper 中找到。这实际上与继承无关。 它是继承的,但在执行类定义时Bar
还不存在。
当您尝试在子类定义语句的类范围中使用属于父命名空间的任何属性时,这与任何属性的工作方式相同。
In [1]: class Foo:
...: def division(self, x, y): return x/y
...:
In [2]: class Bar(Foo):
...: division(1,1)
...:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-8-03e47cf52ab3> in <module>
----> 1 class Bar(Foo):
2 division(1,1)
3
<ipython-input-8-03e47cf52ab3> in Bar()
1 class Bar(Foo):
----> 2 division(1,1)
3
NameError: name 'division' is not defined
要解决这个问题,您可以这样做:
class Bar(Foo):
@Foo.wrapper
def multiplication(self, x, y):
return x * y
或者:
class Bar(Foo):
def multiplication(self, x, y):
return x * y
Bar.multiplication = Bar.wrapper(Bar.multiplication)
关于python - 为什么不是所有的方法都继承自类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64891255/