简体   繁体   English

从 Python object 调用方法

[英]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.所以我有这个 class 用 Python 编写,构造函数在初始化时将字符串作为参数。 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.此 class 具有反转作为参数的相同字符串的方法,但无法将此 class 实例化为 object 并像在其他语言中一样调用该方法。 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上面的print(mypalindrome.func)正在输出这个

<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.您的代码中几乎没有错误mypalindrome有错字,而 func 应该有self作为参数。 Also function is called with () here is the working solution也用()调用 function 这是工作解决方案

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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