从字符串调用方法
如果我有一个 Python 类,并且想根据变量调用其中的函数,我该怎么做?我想象以下可以做到这一点:
class CallMe: # Class
def App(): # Method one
...
def Foo(): # Method two
...
variable = "App" # Method to call
CallMe.variable() # Calling App()
但它不能。还有其他方法可以做到这一点吗?
If I have a Python class, and would like to call a function from it depending on a variable, how would I do so? I imagined following could do it:
class CallMe: # Class
def App(): # Method one
...
def Foo(): # Method two
...
variable = "App" # Method to call
CallMe.variable() # Calling App()
But it couldn't. Any other way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以这样做:
getattr 是一个内置方法,它返回对象的命名属性。本例中的值是一个方法对象,您可以使用 () 调用
You can do this:
getattr is a builtin method, it returns the value of the named attributed of object. The value in this case is a method object that you can call with ()
您可以使用 getattr,也可以将绑定或未绑定的方法分配给变量。绑定方法与类的特定实例绑定,而未绑定方法与类绑定,因此您必须将实例作为第一个参数传递。
例如
You can use getattr, or you can assign bound or unbound methods to the variable. Bound methods are tied to a particular instance of the class, and unbound methods are tied to the class, so you have to pass an instance in as the first parameter.
e.g.
您的班级已被宣布为“旧式班级”。我建议你把所有的课程都设为“新式课程”。
新旧类之间的区别在于新式类可以使用继承,但您可能不会立即需要继承。但这是一个值得养成的好习惯。
创建新样式类所需要做的就是:使用 Python 语法表明它继承自“object”。您可以通过在类名后面加上括号并将名称 object 放在括号内来实现此目的。就像这样:
正如我所说,您可能不需要立即使用继承,但这是一个值得养成的好习惯。 StackOverflow 上有几个问题,大意是“我正在尝试做 X,但它不起作用”,结果发现这个人编写了一个旧式的类。
Your class has been declared as an "old-style class". I recommend you make all your classes be "new-style classes".
The difference between the old and the new is that new-style classes can use inheritance, which you might not need right away. But it's a good habit to get into.
Here is all you have to do to make a new-style class: you use the Python syntax to say that it inherits from "object". You do that by putting parentheses after the class name and putting the name object inside the parentheses. Like so:
As I said, you might not need to use inheritance right away, but this is a good habit to get into. There are several questions here on StackOverflow to the effect of "I'm trying to do X and it doesn't work" and it turns out the person had coded an old-style class.
你的代码看起来不像Python,也许你想这样做?
Your code does not look like python, may be you want to do like this?