Say I have defined a class myself and I defined a __repr__
method for it. I want to about convert it back to my object. I know that object serialization may be a good way of doing so (using the json
module) but is there anyway I can use the built-in eval
function to achieve this?
Asked
Active
Viewed 213 times
2
-
I am sorry for ambiguity here, What I mean is I want to make my object eval-able here. – Bob Fang Feb 01 '13 at 23:27
1 Answers
4
Write your __repr__()
so it creates a valid Python expression for instantiating your object.
class MyClass(object):
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "%s(%r, %r)" % (type(self).__name__, self.a, self.b)
Obviously this relies on the values you're using having their own reasonable repr()
.
You don't have to define any special eval()
—just pass in whatever you get from repr()
.

kindall
- 178,883
- 35
- 278
- 309
-
if you try this, you will get an error saying NameError: name 'instance' is not defined – Bob Fang Feb 01 '13 at 23:26
-
There is not anything called `instance` in that code, so that's not where that error is coming from. – kindall Feb 02 '13 at 01:07
-
1