在类错误中调用类方法

时间:2017-10-24 21:56:26

标签: python python-3.x class oop

class String(object):
    def __init__(self, text):
        self.text = text

    def __repr__(self):
        return "{}".format(self.text)

    def reverse(self):
        return self.text[::-1]

    def isPalindrome(self):
        return (self.reverse(self.text) == self.text)


def main():
    string = String(input("Write a String: "))

    if(string.isPalindrome()):
        print("The string {{}} IS a Palindrome".format(string))
    else:
        print("The string {{}} is NOT Palindrome".format(string))

我有这个代表String的classe,我想通过调用方法isPalindrome来检查对象是一个回文。但是当我打电话给string.isPalindrome时我得到了这个错误:

Traceback (most recent call last):
  File "palindrome.py", line 23, in <module>
    main()
  File "palindrome.py", line 17, in main
    if(string.isPalindrome()):
  File "palindrome.py", line 12, in isPalindrome
    return (self.reverse(self.text) == self.text)
TypeError: reverse() takes 1 positional argument but 2 were given

1 个答案:

答案 0 :(得分:2)

错误来自这一行:

return (self.reverse(self.text) == self.text)

为此改变:

return (self.reverse() == self.text)

self可能真的令人困惑,这是一个非常好的article来理解它是如何工作的。您理解这一点,请查看reverse()定义:

def reverse(self):
    return self.text[::-1]

如您所见,self.text已经分配。调用它时无需将其传递给函数。