简体   繁体   English

在类方法中将方法名称作为参数传递时出错

[英]Error passing a method name as argument in a class method

Well I am trying to do this: 好吧,我正在尝试这样做:

class Foo(object):
    def method1(self):
        print "method1"
    def method2(self):
        print "method2"        

class Fo1(object):
    def __init__(self):
        self.a = Foo()
    def classMethod(self, selection):
        self.a.selection()

A = Fo1()
A.classified('method2')

I got this error: 我收到此错误:

--> AttributeError: 'Fo1' object has no attribute 'selection'

I don't want to use this (seems to me, more coding): 我不想使用它(在我看来,更多的编码):

 def classified(self,selection):
    if selection == "method1": self.a.method1()
    elif selection == "method2": self.a.method2()

How should I code the method so that I can pass the method name as an argument? 我应该如何编码方法,以便可以将方法名称作为参数传递? Thanks! 谢谢!

You can use getattr to do this, eg 您可以使用getattr来执行此操作,例如

def classMethod(self, selection):
    getattr(self.a, selection)()

getattr takes an object an attribute name and returns the attribute, which you can then call. getattr为对象获取一个属性名称,然后返回该属性,然后可以调用该属性。

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

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