来自派生类实例的泡菜基类
我的基类看起来像:
@dataclass
class A:
var1: List[float]
var2: float
派生的类看起来像:
class B(A):
def __init__(self, v1):
super().__init__(v1, 0)
def process():
pass
我想要一种泡菜b
实例的方法,以便仅需要类a
才能取消它。我知道Python不支持升级,但是有办法实现我想要的东西吗?我想要以下内容:
l1 = [1., 2., 4.]
obj = B(l1)
with open(filename, 'wb') as pickleFile:
pickleFile.write(pickle.dumps((A)obj))
后续问题。这样的事情有效,但我不确定后果:
l1 = [1., 2., 4.]
obj = B(l1)
obj.__class__ = A
with open(filename, 'wb') as pickleFile:
pickleFile.write(pickle.dumps(obj))
任何帮助都将不胜感激。谢谢!
My base class looks like :
@dataclass
class A:
var1: List[float]
var2: float
and derived class looks like :
class B(A):
def __init__(self, v1):
super().__init__(v1, 0)
def process():
pass
I want a way to pickle an instance of B
in a way such that only class A
is required to unpickle it. I understand that python does not support upcasting but is there a way to achieve what I want? I want something like the following:
l1 = [1., 2., 4.]
obj = B(l1)
with open(filename, 'wb') as pickleFile:
pickleFile.write(pickle.dumps((A)obj))
Followup question. something like this works but I am not sure of the consequences:
l1 = [1., 2., 4.]
obj = B(l1)
obj.__class__ = A
with open(filename, 'wb') as pickleFile:
pickleFile.write(pickle.dumps(obj))
Any help would be appreciated. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用Module-level dataclasses.asdict.asdict.asdict.asdict> ()实用程序功能将
b
dataclass对象转换为dict
(这是默认的出厂函数),然后使用它来创建一个base类实例。这与“ upcasting”b
实例中的“ upcasting”与a
实例不完全相同,但效果相似。You can effectively do what you want by using the module-level dataclasses.asdict() utility function to convert the
B
dataclass object into adict
(which is the default factory function), and then use that to create a base class instance. This isn't quite the same thing as "upcasting" theB
instance into anA
instance, but effect is similar.