简体   繁体   English

Python raw_input()字符串作为实例名称

[英]Python raw_input() string as instance name

I'm working on a PhoneBook in python and I have a class from which I want the user to call instances via raw_input. 我正在使用python开发电话簿,并且有一个我希望用户通过raw_input调用实例的类。

For example 例如

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

Is it possible to use the string to call pb.Add()? 是否可以使用字符串调用pb.Add()?

Thanks in advance! 提前致谢!

Use getattr : 使用getattr

getattr(pb, Input)()

getattr returns the function , and doesn't call it. getattr返回该函数 ,并且不调用它。 Hence the extra () at the end. 因此,多余的()位于末尾。

Some other things: 其他一些事情:

  • You should return "name added" instead of printing it. 您应该返回 "name added"而不是打印出来。
  • Leave uppercased-named variables for classes :). 保留类大写命名的变量:)。 Lowercase for functions, etc. 小写的功能等

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

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