Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6383193
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T02:37:06+00:00 2026-05-25T02:37:06+00:00

Possible Duplicate: Calling a function from a string with the function's name in Python

  • 0

Possible Duplicate:
Calling a function from a string with the function's name in Python

I think I could write some terrible code that would do this, but I’d much rather see the ‘clean version’.

What seems the good approach to me, is to make a dict that holds the various functions that a given object can use. Then when the user is instructed to tell the object what it’s doing, it spits out a menu based on that dict.

I searched around a bit and didn’t really see something that applied to me so I figured I’d give it a try. Well, it didn’t work.

class Man(object):
    def __init__(self):
        self.cmds = ['foo', 'bar']

    def foo(self):
        print "Foo called."

    def bar(self):
        print "Bar called."

    def junk(self):
        print "Junk called." ##not in dict, on purpose, will explain

    def menu(self):
        while True:
            print "List of actions:"
            for acts in self.cmds:
                print acts
            cmd = raw_input("> ")
            if cmd in self.cmds:
                cmd()    ##doesn't work.
                         ##neither did self.cmd() (got AttributeError, obviously)

                result = getattr(self, cmd)() ## this works! thanks cdhowie
            else:
                pass

Stick = Man()
Stick.menu()

In case it isn’t obvious, the program gives TypeError whenever I enter something which the if-else sees to be True – in this case, entering either ‘foo’ or ‘bar’.
Here’s the thing, is that I know I could just write a big long ugly if-else thing here and make this example work – but I want to be able to just append/remove from self.cmds to alter the object’s functionality. Hence the third function Junk(); Stick can’t access ‘Junk()’ from the current dict-menu, but with a little self.cmds.append action I want it to be able to.

Freaking Python, how do they work? Is this the right way to go about this, or is there a simpler method?

EDIT: My answer was found in the magic of getattr. Thanks cdhowie. The trick was to change the while loop to have this bit: result = getattr(self, cmd)()

I know now my next mission is to finally figure out what getattr() actually does. Forgive my noob status, heh, I know not what I code 🙂

FINAL EDIT: while cdhowie’s example works with the original program, I have since found that ders’ answer allows me to do things functionally that I wouldn’t have been able to do with getattr(); ders’ solution made it easier for me to use functions in other objects in Man’s init – I think that’s called ‘object composition’ right? At any rate getattr() would AttributeError any functions added to self.cmds from anywhere but Man. Or I could just be doing it weird again. But suffice to say, ders FTW.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T02:37:07+00:00Added an answer on May 25, 2026 at 2:37 am

    In your example Man.cmds is a list not a dictionary. So they TypeError is raised when the string in the self.cmds list is called as a function.

    Create a dictionary with the function name as a string paired with the function itself.

        def __init__(self):
            self.cmds = {'foo':self.foo, 'bar':self.bar}
    

    Within your Menu function, check if the user has entered in a valid function name. If so pull it out of the dictionary and call it.

                if cmd in self.cmds:
                    command = self.cmds[cmd]
                    command()
                else:
                    pass
    

    To dynamically add the junk function, you could then update cmds:

    Stick.cmds.update({'junk':Stick.junk})
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: Calling Python from Objective-C I'm a long-time Python programmer and short-time Cocoa
Possible Duplicate: Calling a webservice that uses ISO-8859-1 encoding from WCF I am trying
Possible Duplicate: Calling a method named “string” at runtime in Java and C I
Possible Duplicate: How to decode string to XML string in C# I'm calling a
Possible Duplicate: WPF MessageBox window style For some reason the MessageBox that comes with
Possible Duplicate: Remove from the array elements that are repeated. in Ruby I would
Possible Duplicate: why does initializing subclasses require calling the super class's same init function?
Possible Duplicate: How do I calculate someone's age in C#? Maybe this could be
Possible Duplicate: How do you send email from a Java app using Gmail? How
Possible Duplicate: JavaScript: var functionName = function() {} vs function functionName() {} What's the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.