[英]How can I convert <class 'str'> into <class '__main__'> in Python
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.对于变量“c”,我想将“b”转换回指针 p10。 So I inspect to return for code
所以我检查返回代码
print(a.x, c.x)
10 10 10 10
I understand that the simple solution is c = a, but I need to convert class 'str' into pointer.我知道简单的解决方案是 c = a,但我需要将 class 'str' 转换为指针。
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.我认为有一个没有额外字典的解决方案。
Python is a strongly typed language (this is not conflict with dynamic types). Python 是一种强类型语言(这与动态类型不冲突)。 After a variable is created, its type is determined.
创建变量后,确定其类型。
str(a)
is not similar to the syntax of (str *) a
in C language. str(a)
与 C 语言中的(str *) a
的语法不同。 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. 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.如果你希望你的
P
object 可以从转换后的str
object 中恢复,你唯一能做的就是自定义P
的__str__
(或示例中的__repr__
) megic 方法来序列化它并使用P
的__init__
方法反序列化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.