class A:
def add_f(self,a,b):
return a+b
class B:
def sum_f(self,a,b,c):
return A.add_f(a,b) + c
B1= B()
print B1.sum_f(1,2,3)
Traceback (most recent call last):
File "C:/Users/wxu/Documents/test.py", line 10, in <module>
print B1.sum_f(1,2,3)
File "C:/Users/wxu/Documents/test.py", line 7, in sum_f
return A.add_f(a,b) + c
TypeError: unbound method add_f() must be called with A instance as first argument (got int instance instead)
Run Code Online (Sandbox Code Playgroud)
当我没有 sum_f(self,a,b,c) 的 self 时,它给了我这个错误:
Traceback (most recent call last):
File "C:/Users/wxu/Documents/test.py", line 10, in <module>
print test1.sum_f(1,2,3)
TypeError: sum_f() takes exactly 3 arguments (4 given)
Run Code Online (Sandbox Code Playgroud)
这是为什么?那么如何在B类中调用A类的add_f函数呢?感谢您的帮助。
有几件事。
self第一个参数。A()当您在 B 类中呼叫时,这也适用。修改后的代码:
class A:
def add_f(self, a, b):
return a + b
class B:
def sum_f(self, a, b, c):
return A().add_f(a, b) + c
print B().sum_f(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)
更新:感谢您接受我的建议,但您仍然遗漏了一些东西。在类 B 中,您调用类 A 中的方法,但也需要括号!在 B 类中,这样调用 A 类:
A().add_f(a, b)
| 归档时间: |
|
| 查看次数: |
33219 次 |
| 最近记录: |