Python:如何将类变量设置为相同类型的另一个类
有没有一种简单的方法可以将一个类的属性设置为同一个类的另一个实例Python:如何将类变量设置为相同类型的另一个类,python,Python,有没有一种简单的方法可以将一个类的属性设置为同一个类的另一个实例 class Foo: def __init__(self, a, b): self.a = a self.b = b def main(): classOne = Foo(1,2) classTwo = Foo(3,4) # DESIRED: classOne = classTwo # How can I easily set the 'a' and '
class Foo:
def __init__(self, a, b):
self.a = a
self.b = b
def main():
classOne = Foo(1,2)
classTwo = Foo(3,4)
# DESIRED:
classOne = classTwo # How can I easily set the 'a' and 'b' of classOne = classTwo?
if __name__ = "__main__":
main()
我知道这样做会奏效:
classOne.a = classTwo.a
classOne.b = classTwo.b
但是,对于具有更多变量的类,有没有更好的方法来实现这一点
谢谢你的帮助 这就是你想要的吗:
import copy
classOne = copy.deepcopy(classTwo)
看看这上面的图片。深度副本将创建一个新类(您正在将其设置为classOne
)实例,该实例的属性值与classTwo
的属性值相同
import copy
class Foo:
def __init__(self, a, b):
self.a = a
self.b = b
def main():
classTwo = Foo(3,4)
classOne = copy.deepcopy(classTwo)
听起来你要找的东西很有魅力。非常感谢。