Hey just wondering if you can do something like that with variables for example

class test(object):
    a = 55
    def dispmenu(self): print self.a

instance = test()

How would i be able to call "instance.dispmenu()" without having to type that.
Some things i have tried

action1 = instance.dispmenu()
print action1

This does run the instance.dispmenu() but it runs it on the "action1 =" lines not the action1 line which doesn't seem to do anything. Also the "print action1" line outputs 'None'

action2 = dispmenu()
print action2

This fails on the first line with "NameError: name 'dispmenu' is not defined"

So then i tried

action3 = 'dispmenu()'
print action3

The print line does output dispmenu() but this fails on line 3 with "AttributeError: 'test' object has no attribute 'action3'"

I didn't expect any of these to work but i thought i may as well try before asking. I'm sure I'm either missing something or its just not possible any help would be great.

Wow. I am puzzled.

instance.dispmenu()#displays menu
dm()#displays menu too
eval('instance.'+dms+'()')# displays menu too
getattr(instance,"dispmenu")() # displays menu too

I'm not getting your results:

class test(object):
    a = 55
    def dispmenu(self): print self.a

>>> instance = test()
>>> instance.dispmenu()
>>> action1 = instance.dispmenu()

>>> print action1

Here's what I think you want to do:

>>> action1 = instance.dispmenu
>>> action1()

So the way to read this is, action1 is assigned to instance.dispmenu, and then the () force calling action1.

Does that help?


This article has been dead for over six months. Start a new discussion instead.