故意尝试破坏Python类继承,不明白为什么会这样破坏
我正在探索 Python 类继承的限制,因此我编写了一个小测试来看看我可以摆脱多少问题 - 重新声明属性和重写函数。
class A:
val : int = 3
def foo(x: int):
print(x)
class B(A):
val : str = 'python'
def foo(x: str):
print(x)
a = A()
b = B()
a.foo(5)
b.foo('test')
print(a.val)
print(b.val)
结果的输出令人惊讶。我本以为重新声明属性会出现某种异常,但我得到的是:
Traceback (most recent call last):
File "c:\Development\Playground\hello.py", line 12, in <module>
a.foo(5)
TypeError: A.foo() takes 1 positional argument but 2 were given
我不明白它如何解释我为 a.foo(5)
提供两个位置参数。当然我想打破它,但我仍然想理解。
I'm exploring the limits of Python class inheritance, so I wrote a small test to see how much I can get away with - redeclaring properties and overriding functions.
class A:
val : int = 3
def foo(x: int):
print(x)
class B(A):
val : str = 'python'
def foo(x: str):
print(x)
a = A()
b = B()
a.foo(5)
b.foo('test')
print(a.val)
print(b.val)
The resulting output is surprising. I would have expected some kind of exception for redeclaring the property, but instead I get:
Traceback (most recent call last):
File "c:\Development\Playground\hello.py", line 12, in <module>
a.foo(5)
TypeError: A.foo() takes 1 positional argument but 2 were given
I don't see how it interpreting that I am providing two positional arguments for a.foo(5)
. Granted I am trying to break it but I still want to understand.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要实例方法的 self 参数。
输出:
You need a self parameter for instance methods.
Output:
现在我知道您不是在寻找修复程序,而是关于解释器在做什么的想法,我可以借此代码的一行:
a.foo(5)
此行只是一条 nice 供美国程序员表达在实例上调用方法(
foo
)的想法(a
)。这是句法糖,我想想到的解释器将文本转换为本文:a.foo(a,5)
,然后对此进行编译。现在,您可以看到,当您将该代码行与定义的方法进行比较时:
def foo(x:int):
解释器将说该方法采用一个位置参数(<代码> x )但是 you 给它两个:(a,5)
Now that I know you are not looking for a fix, but an idea about what the interpreter is doing I can walk you through one line of your code:
a.foo(5)
This line is just a nice way for us programmers to express the idea of calling a method (
foo
) on an instance (a
). This is syntactic sugar and I like to think of the interpreter transforming that text to this text:A.foo(a, 5)
and then compiling that. Now you can see, when you compare that line of code to the method that you defined:
def foo(x: int):
that the interpreter is going to say that the method takes one positional argument (x
) but you are giving it two:(a, 5)
我认为出现错误是因为自动通过了班级的函数,因此产生了错误
I think the error is produced because self was automatically passed since it's a function of a class so your functions have to take self as their first argument