简体   繁体   中英

Call a method from a Python object

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM