简单但太多的方法调用位置参数 [英] Simple but too many positional arguments for method call
问题描述
-
谁能解释为什么
TypeError
是
fib()接受1个位置参数,但给定2个参数.
fib() takes 1 positional argument but 2 were given`
当我只给它一个参数时=> self.fib(self.n-1)
!
when I'm only giving it ONE argument => self.fib(self.n - 1)
!
此外,在保留类实例化的同时,您能否提出解决此问题的解决方案?
Also, while keeping the instantiation of the class, can you suggest your solution to fix this?
我觉得自我"使用过多,尤其是在添加的更多方法中.可以改善吗?
I feel the "self" is being used too much, especially with the more methods I add. Can that be improved?
只是想把我的头放在一些基础知识上!感谢所有反馈.
Just trying to wrap my head around some basics! All feedback is appreciated.
class math_func:
def __init__(self, n: "int" = 6, output: "list" = []):
self.n = n
self.output = output
def fib(self):
print("Current output is:", self.output)
if self.n == 0:
return self.output
else:
if len(self.output) < 2:
self.output.append(1)
self.fib(self.n - 1)
else:
last = self.output[-1]
second_last = self.output[-2]
self.output.append(last + second_last)
self.fib(self.n - 1)
return self.output
first_func = math_func(n=9)
print(first_func.fib())
推荐答案
方法的第一个参数是 self
,它引用方法被调用的 object 上.如果看起来像您希望传递一个参数(看起来像 n
),则需要在方法的签名中包含该参数.
The first argument of a method is self
, which refers to the object the method is being called on. If, as it appears, you wish to pass an argument (n
, it looks like), you need to include that in the method's signature.
这篇关于简单但太多的方法调用位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!