generating method names 'dynamically'

D

Daniel Nogradi

Is it possible to have method names of a class generated somehow dynamically?

More precisely, at the time of writing a program that contains a class
definition I don't know what the names of its callable methods should
be. I have entries stored in a database that are changing from time to
time and I always want to be able to call (from another program) those
method names which are at the moment present in the database.
 
F

Farshid Lashkari

Is it possible to have method names of a class generated somehow dynamically?

If you don't know the name of the method ahead of time, how do you write
the code for it? Do you use some dummy name? If so, once you have the
name determined then you could use setattr to set the method name.
Here's a simple example:

class MyClass:
def DummyMethodName(self): pass

setattr(MyClass,'NewMethodName',MyClass.DummyMethodName)

-Farshid
 
M

Murali

import inspect

x = ABC() # create an instance of class ABC
print inspect.getmembers(x,inspect.ismethod)
 
M

Murali

x.__class__.__dict__[mname](x,*args,**kwargs)

here
x is an instance of a class FOO
FOO has a method "bar" (if the value of mname is "bar")
args is a tuple whose length is the number of positional arguments
accepted by bar
kwargs is a dictionary corresponding to the keyword arguments accepted
by bar.

Hope this answers your questions.

- Murali
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,282
Messages
2,571,404
Members
48,096
Latest member
Kenkian2628

Latest Threads

Top