MarMan29
MarMan29

Reputation: 729

Calling function from string name within object

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.

Upvotes: 0

Views: 64

Answers (2)

Randy Arguelles
Randy Arguelles

Reputation: 225

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]

Upvotes: 1

Kenji Noguchi
Kenji Noguchi

Reputation: 1773

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

Upvotes: 2

Related Questions