bkvaluemeal
bkvaluemeal

Reputation: 448

Python append function as dot notation

def do_something(obj, func):
    obj.func()

My question is how do I call func on obj? func is a function of obj. Is this even possible?

Upvotes: 7

Views: 2047

Answers (2)

hygull
hygull

Reputation: 8740

Anyway func is a method defined on obj so you can directly call it using func() not by obj.func() as func itself is obj.func according to your question.

I have cleared this in the below 2 examples executed on Python interactive termainal.

First I have defined a simple class then I have tried to access its instance method according to this question.

>>> # Defining class
... 
>>> class MyClass(object):
...     def __init__(self):
...         self.name = "Rishikesh Agrawani"
...         self.age = 25
...     def doStuff(self):
...         print "DETAILS:\n"
...         print "NAME: %s" % (self.name)
...         print "AGE : %d" % (self.age)
... 
>>> # Instantiation
... 
>>> obj = MyClass()
>>> func = getattr(obj, "doStuff");
>>> func()
DETAILS:

NAME: Rishikesh Agrawani
AGE : 25
>>> 

Finally

>>> def do_something(obj, func):
...     obj.func()
... 
>>> do_something(obj, func)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in do_something
AttributeError: 'MyClass' object has no attribute 'func'
>>> 
>>> def do_something(obj, func):
...     print obj, func
... 
>>> do_something(obj, func)
<__main__.MyClass object at 0x100686450> <bound method MyClass.doStuff of <__main__.MyClass object at 0x100686450>>
>>> 
>>> 
>>> def do_something(obj, func):
...     func()
... 
>>> do_something(obj, func)
DETAILS:

NAME: Rishikesh Agrawani
AGE : 25
>>> 

Upvotes: 0

101
101

Reputation: 8999

If func is an actual function of obj you can simply call it:

func()

An example:

class Klass(object):
    def say_hi(self):
        print 'hi from', self

func = Klass().say_hi
func()   # hi from <__main__.Klass object at 0x024B4D70>

Otherwise if func is the name of the function (a string) then this will get it and call it:

getattr(obj, func)()

Upvotes: 5

Related Questions