python Python对象转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2153295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python object conversion
提问by zoli2k
Assume that we have an object kof type class A. We defined a second class B(A). What is the best practice to "convert" object kto class Band preserve all data in k?
假设我们有一个k类型为 的对象class A。我们定义了第二个class B(A)。将对象“转换”k为class B并保留所有数据的最佳实践是什么k?
采纳答案by jsbueno
This does the "class conversion" but it is subject to collateral damage. Creating another object and replacing its __dict__as BrainCore posted would be safer - but this code does what you asked, with no new object being created.
这会进行“阶级转换”,但会受到附带损害。创建另一个对象并将其替换__dict__为 BrainCore 发布会更安全 - 但此代码执行您的要求,没有创建新对象。
class A(object):
pass
class B(A):
def __add__(self, other):
return self.value + other
a = A()
a.value = 5
a.__class__ = B
print a + 10
回答by BrainCore
a = A() # parent class
b = B() # subclass
b.value = 3 # random setting of values
a.__dict__ = b.__dict__ # give object a b's values
# now proceed to use object a
Would this satisfy your use case? Note: Only the instance variables of b will be accessible from object a, not class B's class variables. Also, modifying variables in a will modify the variable in b, unless you do a deepcopy:
这会满足您的用例吗?注意:对象 a 只能访问 b 的实例变量,而不能访问 B 类的类变量。此外,修改 a 中的变量将修改 b 中的变量,除非您进行深拷贝:
import copy
a.__dict__ = copy.deepcopy(b.__dict__)
回答by Yaniv K.
class A:
def __init__(self, a, b):
self.a = a
self.b = b
class B(A):
def __init__(self, parent_instance, c):
# initiate the parent class with all the arguments coming from
# parent class __dict__
super().__init__(*tuple(parent_instance.__dict__.values()))
self.c = c
seld.d = d
a_instance = A(1, 2)
b_instance = B(a_instance, 7)
print(b_instance.a + b_instance.b + b_instance.c)
>> 10
Or you could have a sperate function for this:
或者你可以有一个单独的功能:
def class_converter(convert_to, parent_instance):
return convert_to(*tuple(parent_instance.__dict__.values()))
class B(A):
def __init__(self, *args):
super().__init__(*args)
self.c = 5
But using the 2nd method, I wasn't able to figure out how to pass additional values
但是使用第二种方法,我无法弄清楚如何传递附加值

