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?
When you use dot notation, you indicate to Python that you want to either run a particular operation on, or to access a particular property of, an object type. Python knows how to infer the object type on which this operation is being run because you use dot notation on an object.
Dot notation is one way to access a property of an object. To use dot notation, write the name of the object, followed by a dot (.), followed by the name of the property.
It's precisely because Python is all about readability that there is no dotted access for dict keys.
The append() method appends an element to the end of the list.
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)()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With