So I have this class written in Python with a constructor that takes a string as an argument when initialized. This class has a method for reversing the same string that was taken as an argument, but am not able to instantiate this class into an object and call the method like in other languages. Please help
class Palindrome:
##Constructor for taking string argument
def __init__(self, name):
self.myname=name
def func(myname):
return (myname[::-1])
##Take a string as a argument from user and use it in the constructor
uname=input("Enter name to reverse?")
##Trying to call method from a python object
Palindrome mypalidrome=Palindrome(uname)
print(mypalindrome.func)
The above print(mypalindrome.func) is outputting this instead
<bound method Palindrome.func of <__main__.Palindrome object at 0x00221F10>>
asked Mar 7, 2021 at 10:20
user14187680
1 Answer 1
There are few mistakes in your code mypalindrome has a typo and func should have self as parameter. Also function is called with () here is the working solution
class Palindrome:
##Constructor for taking string argument
def __init__(self, name):
self.myname=name
def func(self):
return (self.myname[::-1])
##Take a string as a argument from user and use it in the constructor
uname=input("Enter name to reverse?")
mypalindrome =Palindrome(uname)
print(mypalindrome.func())
answered Mar 7, 2021 at 10:25
Macintosh_89
7389 silver badges26 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
Palindrome mypalidrome=Palindrome(uname)?print(mypalindrome.func(uname)). Also, you're not actually usingself.mynameanywhere.