Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python原始输入()字符串作为实例名称_Python_Oop_Instance - Fatal编程技术网

Python原始输入()字符串作为实例名称

Python原始输入()字符串作为实例名称,python,oop,instance,Python,Oop,Instance,我正在用python编写一个电话簿,我有一个类,希望用户通过原始输入调用该类的实例 比如说 class PhoneBook(): def Add(self): print "Name added" def main(): pb = PhoneBook() Input = raw_input() #Here I want to call pb.add() (and in the future other alternatives) #us

我正在用python编写一个电话簿,我有一个类,希望用户通过原始输入调用该类的实例

比如说

class PhoneBook():

    def Add(self):
        print "Name added"

def main():
    pb = PhoneBook()
    Input = raw_input()
    #Here I want to call pb.add() (and in the future other alternatives)
    #using the string Input. As I want it (but I know doesn't work): pb.Input[0]
    #provided the user types Add
是否可以使用该字符串调用pb.Add()

提前谢谢

使用:

getattr
返回函数,不调用它。因此,在最后额外的
()

其他一些事情:

  • 您应该返回
    “name added”
    ,而不是打印它
  • 为类保留大写的命名变量:)。函数等的小写字母

是的,打印出来只是为了测试。好的,谢谢你的帮助@英根也这么认为:p。没问题:DLets说我想向Add()函数发送部分输入,因为Add()将向电话簿中添加姓名,我该怎么做?@ingen我不确定我是否完全理解您的意思,但您可以允许函数使用特定的参数(或“参数”,如果您愿意的话)。对不起,我现在很累,我解决了它。当然我只需要把它们加在括号里。。。
getattr(pb, Input)()