繁体   English   中英

从 Python object 调用方法

[英]Call a method from a Python object

所以我有这个 class 用 Python 编写,构造函数在初始化时将字符串作为参数。 此 class 具有反转作为参数的相同字符串的方法,但无法将此 class 实例化为 object 并像在其他语言中一样调用该方法。 请帮忙

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)

上面的print(mypalindrome.func)正在输出这个

<bound method Palindrome.func of <__main__.Palindrome object at 0x00221F10>>

您的代码中几乎没有错误mypalindrome有错字,而 func 应该有self作为参数。 也用()调用 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