简体   繁体   English

如何在python中克隆一个类的对象?

[英]how do I make an object of a class clone itself in python?

I am creating a game that has a 'Battlefield.'我正在创建一个具有“战场”的游戏。 I created a class for it:我为它创建了一个类:

class Battlefield:
    units = [[Warrior1, Warrior2]]

I am creating a function that would clone the units on the battlefield, so the new Battlefield.units would be:我正在创建一个函数来克隆战场上的单位,所以新的 Battlefield.units 将是:

print (Battlefield.units)
[[Warrior1, Warrior2], [Warrior1, Warrior2]]

'Warrior1'is something like 'Warrior1'有点像

Warrior1 = [1, 3, 2, 5, 6]

What makes this difficult, is I need to be able to adjust the stats for ONLY the first Warrior1, without adjust the stats of the second Warrior1.使这变得困难的是,我需要能够仅调整第一个 Warrior1 的统计数据,而无需调整第二个 Warrior1 的统计数据。 All of the questions that I've seen on stack overflow have addressed how to copy a list onto a new list, such as:我在堆栈溢出中看到的所有问题都解决了如何将列表复制到新列表中的问题,例如:

new_list = old_list.copy()

However, I will not be able to reference this new_list in existing functions, since within the game I constantly refer back to the 'Battlefield.unit' object.但是,我将无法在现有函数中引用这个 new_list,因为在游戏中我经常引用回“Battlefield.unit”对象。 In other words, I must clone WITHIN the existing object, all while making the variables within the list somehow distinct from one another so I can alter one without altering the other.换句话说,我必须在现有对象内进行克隆,同时使列表中的变量以某种方式彼此不同,这样我就可以改变一个而不改变另一个。

Please advise.请指教。 Thank you!谢谢!

You can use copy.deepcopy :您可以使用copy.deepcopy

>>> import copy
>>> a = [[1, 2], [3,4]]
>>> b = copy.deepcopy(a)
>>> b[0][0] = 4
>>> a
[[1, 2], [3, 4]]
>>> b
[[4, 2], [3, 4]]

Or for an object oriented approach:或者对于面向对象的方法:

class Warrior():
  def __init__(self):
    pass
  def copy(self):
    return copy.deepcopy(self)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM