简体   繁体   中英

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

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

getattr takes an object an attribute name and returns the attribute, which you can then call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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