Skip to content Skip to sidebar Skip to footer

How To Obtain An Object From A String?

Say I have the following class class Test: def TestFunc(self): print 'this is Test::TestFunc method' Now, I create an instance of the class Test >>> >>

Solution 1:

You cannot with the string alone go back to the same object, because Python does not give you a method to look up objects by memory address.

You can go back to another instance of __main__.Test, provided it's constructor doesn't take any arguments, and look up the method again, but it will not have the same memory address.

You'd have to parse the string for it's components (module, classname, and method name), then use getattr() on the various components, instantiating the class as part of the process. I doubt this is what you wanted though.

Solution 2:

There are several pitfalls to consider:

  • the instance of Test may or may not exist anymore
  • the instance may have been garbage collected
  • the instance may have had the function monkey-patched Test.TestFunc
  • a different object may have been created at 0xb771b28c

Solution 3:

You can use getattr.

    In [1]:
    classTest:
        defTestFunc(self):
            print'this is Test::TestFunc method'

    In [2]: t = Test()

    In [3]: getattr(t, 'TestFunc')
    Out[3]: <bound method Test.TestFunc of <__main__.Test instance at 0xb624d68c>>

    In [4]: getattr(t, 'TestFunc')()
    this is Test::TestFunc method

Post a Comment for "How To Obtain An Object From A String?"