Referencing objects own functions
exarkun at divmod.com
exarkun at divmod.com
Tue Oct 19 11:53:46 EDT 2004
On 19 Oct 2004 08:45:42 -0700, jackson.pip at gmail.com (pip) wrote:
>Hi all,
>
> Pretend I have the following:
>
> class foo:
> commands = [
> 'name': 'help',
> 'desc': 'Print help',
> ]
>
> def print_help(self):
> print "Help is on the way!"
>
> I would like to add another entry to the commands dict. called 'func'
> or something which contains a reference to a function in the foo
> class. What would the entry look like if atall possible?
>
Something like this?
class foo:
def print_help(self):
print "Help is on the way!"
commands = {
"help": print_help}
Note that print_help is a function, not a method, and so commands will contain a reference to a function. This means when you call it you must supply self manually. Another, perhaps easier, approach:
class bar:
def cmd_help(self):
print "Help is on the way!"
def run(self, command):
return getattr(self, "cmd_" + command)()
This takes advantage of the fact that cmd_help is already an entry in a dict - the class's attribute dict - and uses it directly from there.
Jp
More information about the Python-list
mailing list