调用方法不起作用,因为两个位置参数?

时间:2018-03-11 22:56:06

标签: python python-3.x

我对类的工作原理感到困惑,我编写了这段代码但得到了错误信息

pigLatin_class

但是对象确实具有该属性,因为它属于类class pigLatin_class (object): 'class for converting plain text into pig latin' vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"] def __init__ (string): pig = "" movetoend = "" index = 0 def pLatin_converter (string): listeng = string.split() for word in listeng: length = len(word) movetoend = "" index = 0 if word[0] not in vowels: for l in word: if l not in vowels: movetoend = movetoend + l index = index + 1 else: break pig = pig + " " + word[index:length] + movetoend + "ay" elif word[0] in vowels: pig = pig + " " + word[1:length] + "hay" print("pig latin is: " + pig) words = pigLatin_class() words = "Hi I'm Amy" words.pLatin_converter()

words = pigLatin_class("Hi I'm Amy")
words.pLatin_converter()

编辑:好吧,我看到我最初的错误,现在如果我输入

self.view.bounds.height

它说我给了2个位置参数?

2 个答案:

答案 0 :(得分:3)

  

对象确实具有该属性,因为它属于“pigLatin_class”类?

但事实并非如此。您确实创建了pigLatin_class的实例,但随后您立即将其替换为str的实例:

words = pigLatin_class()
words = "Hi I'm Amy"

并且str不是pigLatin_class,并且没有pLatin_converter方法。

我想你想要这样的东西:

words = pigLatin_class("Hi I'm Amy")
words.pLatin_converter()

但是你需要修复一些bug。最重要的是,类的__init__方法必须采用self参数以及string参数,然后需要存储内容 - 包括字符串参数值-on稍后将使用的self

def __init__(self, string):
    self.string = string
    self.pig = ""
    self.movetoend = ""
    self.index = 0

然后,您的方法也将使用self并可以使用这些属性:

def pLatin_converter(self): 
    listeng = self.string.split()
    # etc.

你可能想要这样的东西:

words = pigLatin_class()
words.pLatin_converter("Hi I'm Amy")

在这种情况下,您不会将string作为__init__中的第二个参数并将其存储在self.string中,而是将其作为第二个参数pLatin_converter。希望你现在知道足够的知识,以改变它的方式,并了解其中的差异。

答案 1 :(得分:1)

你正在传递字符串'嗨,我是艾米'到pLatin_converter()方法。

相反,你需要这样做:

class pigLatin_class (object):
    'class for converting plain text into pig latin'


    def __init__ (self, string):

        self.string = string
        self.vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]

    def pLatin_converter(self):
        pig = ""
        movetoend = ""
        index = 0

        listeng = self.string.split()
        for word in listeng:
            length = len(word)
            movetoend = ""
            index = 0
            if word[0] not in self.vowels:
                for l in word:
                    if l not in self.vowels:
                        movetoend = movetoend + l
                        index = index + 1
                    else:
                        break
                pig = pig + " " + word[index:length] + movetoend + "ay"

            elif word[0] in self.vowels:
                pig = pig + " " + word[1:length] + "hay"
        print("pig latin is: " + pig)

words = pigLatin_class("Hi I'm Amy")

words.pLatin_converter()

您需要使用self.var_name定义基于类的变量,然后通过将self作为方法参数传递,您可以在整个类中访问它们。在这种情况下,您将字符串传递给 init ()并将其保存在self.string变量中,然后您可以在调用pLatin_converter()方法时访问它。

相关问题