Python3:对象不会获取参数

时间:2017-08-04 17:48:41

标签: python python-3.6

我正在审核Lynda上的视频,有时候我自己输入的代码不是仅仅运行提供的代码。

教师的代码有效,但我的代码没有。

返回"object does not take parameters"

我的是最重要的,他在底部。

任何人都可以解释一下吗?

    class Fibonnacci():
        def _init_(self, a, b):
            self.a = a
            self.b = b

        def series(self):
            while(True):
                yield(self.b)
                self.a, self.b = self.b, self.a + self.b

    f = Fibonnacci(0, 1)
    for r in f.series():
        if r > 100: break
        print(r, end=' ')
    class Fibonacci():
        def __init__(self, a, b):
            self.a = a
            self.b = b

        def series(self):
            while(True):
                yield(self.b)
                self.a, self.b = self.b, self.a + self.b

    f = Fibonacci(0, 1)
    for r in f.series():
        if r > 100: break    
        print(r, end=' ')

1 个答案:

答案 0 :(得分:0)

The reason is the init function in the class. The way this method works as seen here to let an object be assigned parameters when initialized. I am sure you understand this, but the simple error you made was that it requires 2 underscores on either side to take effect. Like this: __init__. That is the difference between your two codes.

class Fibonnacci():
    def _init_(self, a, b):   #<-- the error is here, should be __init__()
        self.a = a
        self.b = b

    def series(self):
        while(True):
            yield(self.b)
            self.a, self.b = self.b, self.a + self.b

f = Fibonnacci(0, 1)
for r in f.series():
    if r > 100: break
    print(r, end=' ')