python - 为什么不是所有的方法都继承自类?

标签 python python-3.x oop

举个例子:

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/

相关文章:

python - 如何修复 "float() argument must be a string or a number, not ' 时间戳“”错误?

python - 获取 Pandas 中每个标识符的时间序列的最新非 NaN 值

mysql - pip 安装 mysqlclient 失败 "Running setup.py bdist_wheel for mysqlclient ... error"

java - 这是使用验证功能扩展所有 Java Swing GUI 的正确方法吗

oop - 对象如何在Lua中引用自身?

node.js - nodejs 模块及其导出之间的差异

python - 为什么 01, 02, ... 07 在 python 解释器中解析为整数,但 08 和 09 抛出语法错误?

python - 在两个不直接相关的小部件之间进行通信

python - 将列表中的类解压到模块中

python - 无法从奇怪的 json 内容中获取项目