Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python append function as dot notation

Tags:

python

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?

like image 724
bkvaluemeal Avatar asked Jul 22 '15 02:07

bkvaluemeal


People also ask

How do you do dot notation in Python?

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.

How do you write in dot notation?

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.

Can I access Python dictionary with dot?

It's precisely because Python is all about readability that there is no dotted access for dict keys.

What does .append do in Python?

The append() method appends an element to the end of the list.


1 Answers

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)()
like image 116
101 Avatar answered Oct 23 '22 04:10

101