# Get class from globals and create an instancem = globals()['our_class']()
# Get the function (from the instance) that we need to callfunc = getattr(m, 'function_name')
# Call itfunc()
例如:
class A:def __init__(self):pass
def sampleFunc(self, arg):print('you called sampleFunc({})'.format(arg))
m = globals()['A']()func = getattr(m, 'sampleFunc')func('sample arg')
# Sample, all on one linegetattr(globals()['A'](), 'sampleFunc')('sample arg')
如果不是一个类:
def sampleFunc(arg):print('you called sampleFunc({})'.format(arg))
globals()['sampleFunc']('sample arg')
getattr(next((x for x in (f("foo") for f in[locals().get, globals().get,self.__dict__.get, __import__])if x)),"bar")()
我们需要深入调查
getattr(next((x for x in (f("foo") for f in([locals().get, globals().get, self.__dict__.get] +[d.get for d in (list(dd.values()) for dd in[locals(),globals(),self.__dict__]if isinstance(dd,dict))if isinstance(d,dict)] +[__import__]))if x)),"bar")()
def say_hello(name):print 'Hello {}!'.format(name)
# get the function by namemethod_name = 'say_hello'method = eval(method_name)
# call it like a regular function laterargs = ['friend']kwargs = {}method(*args, **kwargs)
class MyClass:def __init__(self, i):self.i = i
def get(self):func = getattr(MyClass, 'function{}'.format(self.i))func(self, 12) # This one will work# self.func(12) # But this does NOT work.
def function1(self, p1):print('function1: {}'.format(p1))# do other stuff
def function2(self, p1):print('function2: {}'.format(p1))# do other stuff
if __name__ == "__main__":class1 = MyClass(1)class1.get()class2 = MyClass(2)class2.get()
class Base:def call_base(func):"""This does not work"""def new_func(self, *args, **kwargs):name = func.__name__getattr(super(self.__class__, self), name)(*args, **kwargs)return new_func
def f(self, *args):print(f"BASE method invoked.")
def g(self, *args):print(f"BASE method invoked.")
class Inherit(Base):@Base.call_basedef f(self, *args):"""function body will be ignored by the decorator."""pass
@Base.call_basedef g(self, *args):"""function body will be ignored by the decorator."""pass
Inherit().f() # The goal is to print "BASE method invoked."
# import module, call module function, pass parameters and print retured value with eval():import randombar = 'random.randint'randint = eval(bar)(0,100)print(randint) # will print random int from <0;100)
# also class method returning (or not) value(s) can be used with eval:class Say:def say(something='nothing'):return something
bar = 'Say.say'print(eval(bar)('nice to meet you too')) # will print 'nice to meet you'
# try/except block can be used to catch both errorstry:eval('Say.talk')() # raises AttributeError because function does not existeval('Says.say')() # raises NameError because the class does not exist# or the same with getattr:getattr(Say, 'talk')() # raises AttributeErrorgetattr(Says, 'say')() # raises NameErrorexcept AttributeError:# do domething or just...print('Function does not exist')except NameError:# do domething or just...print('Module does not exist')