【发布时间】:2021-07-09 17:28:12
【问题描述】:
我是一个没有经验的 Python 用户,遇到了对象实例和类的问题。当我在“父”类(“购物车”)中附加“子”类(“项目”)的一个实例,然后对购物车的实例进行更改时,这也会更改原始的“子” ' 项目,导致全面的指数增长和普遍的悲伤时期。
我很确定这与我对变量的理解有关,但我非常感谢有关最佳实践的反馈,以避免将来发生这种情况。
这是我的代码 sn-p 来显示问题:
# Defining classes
class ShoppingCart(object):
def __init__(self):
self.items = []
def add(self, new_item):
if new_item.name not in [item.name for item in self.items]:
self.items.append(new_item) # I think this makes a pointer to the "new_item" itself
else:
for item in self.items:
if item.name == new_item.name:
item.quantity += new_item.quantity # This then alters the "new_item" as well
def __repr__(self):
for item in self.items:
return f"Shopping cart: {item.name}, Quantity: {item.quantity}"
class Item(object):
def __init__(self, name, quantity):
self.name = name
self.quantity = quantity
def __repr__(self):
return f"Original item: {self.name}, Quantity: {self.quantity}"
# Adding/printing function
def adding_items(shopping_cart, item):
shopping_cart.add(item)
print(item)
print(shopping_cart)
# Defining objects
item_1 = Item(name="First Item", quantity=2)
shopping_cart_1 = ShoppingCart()
# Adding the same item four times, and the original item is changed as well
adding_items(shopping_cart_1, item_1)
# Original item: First Item, Quantity: 2
# Shopping cart: First Item, Quantity: 2
adding_items(shopping_cart_1, item_1)
# Original item: First Item, Quantity: 4
# Shopping cart: First Item, Quantity: 4
adding_items(shopping_cart_1, item_1)
# Original item: First Item, Quantity: 8
# Shopping cart: First Item, Quantity: 8
adding_items(shopping_cart_1, item_1)
# Original item: First Item, Quantity: 16
# Shopping cart: First Item, Quantity: 16
非常感谢任何建议。
谢谢!
丰富
【问题讨论】:
-
“Python 用户在对象实例、类和指针方面遇到问题”python 没有指针。
-
不管怎样,你不明白的到底是什么?您将相同的对象添加到列表中,当然如果您修改该对象,那么它将被修改。你问如何复制一个对象?我认为您应该阅读以下内容:nedbatchelder.com/text/names.html
-
@juanpa.arrivillaga - 谢谢 - 是的,我在问如何复制一个对象,在这种情况下如何复制 item_1,这样,当它添加到 shopping_basket 时,我可以更改购物篮实例不改变原来的。
-
因此,IMO 最好的方法是创建自己的
.copy方法来执行此操作。您可以将copy模块用于可以处理大多数情况的固定(尽管效率低下)函数,即copy.copy用于浅拷贝,copy.deepcopy用于深度拷贝 -
啊,我想我在找 copy.deepcopy([ORIGINAL OBJECT])