How can I convert <class 'str'> into <class '__main__'> in Python

Viewed 37
class P:
    def __init__(self, x):
        self.x = x
    def __repr__(self):
        return f"p{self.x}"
    def a(self):
        print(self.x)        
a = P(10)
print(a, type(a))    # p10 <class '__main__.P'>
b = str(a)
print(b, type(b))    # p10 <class 'str'>

c = ???? 

For variable 'c' I would like to convert 'b' back into pointer p10. So I inspect to return for code

print(a.x, c.x)

10 10

I understand that the simple solution is c = a, but I need to convert class 'str' into pointer.

Solution with dictionary, dynamically adding objects

lst = [1, 3, 7, 4]
d = {}
for i in lst:
    x = P(i)
    d[str(x)] = x
d['p3'].a()
d['p7'].a()

I thought that there is a solution without additional dictionary.

1 Answers

Python is a strongly typed language (this is not conflict with dynamic types). After a variable is created, its type is determined. str(a) is not similar to the syntax of (str *) a in C language. It will not cast the type of object a like C, but constructs a brand-new str object through the parameter a you pass in. The resulting object is independent of a itself.

If you want your P object can be restored from the converted str object, the only thing you can do is customize __str__ (or __repr__ in your example) megic method of P to serialize it and use __init__ method of P to deserialize.

Related