init采用的参数多于定义的参数

时间:2017-04-21 21:57:48

标签: python python-3.x

我一直收到错误

  

init ()需要2个位置参数,但有4个被赋予

每当我运行下面的代码时。我已经搜索了问题,但似乎大多数人在尝试传递对象时遇到此错误。我只是想传递一个字符串。有人可以帮帮我吗?

class pigLatin_class(object):
    def __init__(self,sentence):
        self.sentence=sentence
    def pigLatinConverter(sentence):
        VOWELS=["a","e","i","o","u"]
        sentence=sentence.split()
        Pigword=""
        for word in sentence:
            if VOWELS[0] or VOWELS[1] or VOWELS[2] or VOWELS[3] or VOWELS[4] not in word:
                Pigword+=word[1:] + word[0] + "way" + " "
            elif word[0] in VOWELS:
                Pigword+=word + "hay" + " "
            else:
                for i in range(len(word)):
                    if word[i] in VOWELS:
                        Pigword+=word[i:] + word[0:i] + "ay" + " "
                        break
        return Pigword

p=pigLatin_class("ataruk esteban")
print(p)

更新: 通过评论解决了这个问题。现在,我得到

<__main__.pigLatin_class object at 0x7f...>

1 个答案:

答案 0 :(得分:1)

您打印了对象,这是一个Python句柄。如果您想查看转换结果,现在需要

print(p.pigLatinConverter())

创建对象时,您提供的文本存储在句子属性中。但是,该对象包含许多其他信息,包括对其两种方法的引用( __ init __ 和转换器)。即使这样一个简单的对象也有些复杂,所以我们在任何给定点上如何引用我们想要的部分都非常谨慎。

您还需要更改转换器中的引用,如下所示:

def pigLatinConverter(self):
    VOWELS=["a","e","i","o","u"]
    sentence=self.sentence.split()

请注意,每个类方法都应该将调用对象作为第一个参数(在Python中传统上称为 self ;它 this 在其他一些语言中)。现在,已经将句子存储在调用对象中。

通过这两项更改,我现在可以从您的程序获得输出:

> p=pigLatin_class("ataruk esteban")
> print(p.pigLatinConverter())

tarukaway stebaneway