Calling class method within class error

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))

I have this classe that represents a String and i want to check is a object is a palindrome by calling the method isPalindrome. But when i call the string.isPalindrome i get this error:

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

Upvotes: 0

Views: 362

Answers (1)

scharette
scharette

Reputation: 9977

The error comes from this line:

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

change it for this:

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

self can be really confusing, here is a really good article to understand how it works. Just so you understand, look at reverse() definition:

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

As you can see, self.text is already assigned. No need to pass it to the function when calling it.

Upvotes: 2

Related Questions