0

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
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
instance.action2

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

So then i tried

action3 = 'dispmenu()'
print action3
instance.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.

3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by jrcagle
0

Wow. I am puzzled.

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

I'm not getting your results:

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


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

55
>>> print action1
None

Here's what I think you want to do:

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

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

Does that help?

Jeff

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.