using a string to call a method

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • darktemp
    New Member
    • Feb 2010
    • 25

    using a string to call a method

    Is it possible to use a string to call a method?
    Say I got a string x = txt (which is a known file extension to my program) and I have a method called txt(value). When x changes to doc, is there a way to make my program call to doc(value)? I tried x(value) (which is a nonexistent method) and I get a string object not callable.

    I hope I am clear enough about it. Thanks :].
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    Hi

    You want the eval command.

    Good luck!

    Comment

    • darktemp
      New Member
      • Feb 2010
      • 25

      #3
      Wow that was really quick and nicely made. Thanks :].

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Glenton,

        Although eval will work, getattr() is a much better solution.

        Code:
        >>> class Foo:
        ... 	def __init__(self):
        ... 		pass
        ... 	def test(self):
        ... 		print "It worked!"
        ... 		
        >>> a = Foo()
        >>> getattr(a, "test")()
        It worked!
        >>>

        Comment

        • Glenton
          Recognized Expert Contributor
          • Nov 2008
          • 391

          #5
          Oh, I misunderstood the questions! Nice one.

          Comment

          Working...