Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access a object's method when the method's name is in a variable?

Tags:

python

Say I have a class object named test.

test has various methods, one of them is whatever() .

I have a variable named method = "whatever"

How can I access the method using the variable with test?

Thanks!

like image 882
nubela Avatar asked Dec 23 '09 19:12

nubela


People also ask

How do you access the methods of an object?

Object Methods in JavaScript can be accessed by using functions. Functions in JavaScript are stored as property values. The objects can also be called without using bracket ().

How do you call an object's method?

Calling an object's method is similar to getting an object's variable. To call an object's method, simply append the method name to an object reference with an intervening '. ' (period), and provide any arguments to the method within enclosing parentheses.

Which operator is used to access a variable or a method from an object?

Simply the dot operator acts as an access provider for objects and classes. The usage of the above operator is as below. It separates a function and variable from an instance variable.


1 Answers

Get the attribute with getattr:

method = "whatever"
getattr(test, method)

You can also call it:

getattr(test, method)()
like image 170
Ned Batchelder Avatar answered Oct 01 '22 16:10

Ned Batchelder