0

I have the following two classes:

class A(object):
   def caller(self,name):
      # want to invoke call() here when name="call"

class B(A):
   def call(self):
      print("hello")

Given the following:

x= B()
x.caller("call") # I want to have caller() invoke call() on the name.

I don't want to check the value of name I want it to automatically invoke the the given string as a function on self.

2 Answers 2

2

Use __getattribute__

class A(object):
   def caller(self,name):
      self.__getattribute__(name)()

class B(A):
   def call(self):
      print("hello")

x= B()
x.caller("call")

Output

hello
Sign up to request clarification or add additional context in comments.

1 Comment

Why not getattr(self, name)()?
1

can also use eval

class A(object):
   def caller(self,name):
      eval('self.%s()' % name)


class B(A):
   def call(self):
      print("hello")


x= B()
x.caller("call")

output

hello [Finished in 0.6s]

1 Comment

Hi Randy is this faster than the above?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.