gpt4 book ai didi

python-3.x - 在 Python 中更改另一个类中的属性

转载 作者:行者123 更新时间:2023-12-04 00:49:26 25 4
gpt4 key购买 nike

我一直在尝试从类 Pod 更改类 Inventory 中的列表,但是我收到一个错误,提示我从一个空集合中弹出。无论如何,我可以从我知道已填充的 Inventory 实例的列表中弹出吗?本质上,我正在尝试将小部件从 Inventory 转移到 Pod。

class Widget():

def __init__(self):
self.cost = 6
self.value = 9


class Inventory():

def __init__(self):
self.widgets_inv = []
self.cost_inv = 0
self.value_inv = 0

def buy_inv(self):
x = int(input("How many widgets to you want to add to inventory? "))
for i in range(0, x):
self.widgets_inv.append(Widget())

def get_inv(self):
print("You have " + str(len(self.widgets_inv)) + " widgets in inventory.")

def cost_of_inv(self):
cost_inv = len(self.widgets_inv) * Widget().cost
print("The current cost of your inventory is: " + cost_inv + " USD.")

def value_of_inv(self):
val_inv = len(self.widgets_inv) * Widget().value
print("The current value of your inventory is: " + val_inv + " USD.")

class Pod():
"""A pod is a grouping of several widgets. Widgets are sold in pods"""

def __init__(self):
self.pod = []

def creat_pod(self):
x = int(input("How many widgets would you like to place in this pod? "))
for i in range(0, x):
self.pod.append(Widget())
Inventory().widgets_inv.pop()

最佳答案

您应该修改 creat_pod-method,以便您可以移交 Inventory-object。这允许您在调用 creat_pod-method 之前将小部件添加到库存对象:

def creat_pod(self, inventory):
x = int(input("How many widgets would you like to place in this pod? "))
for i in range(0, x):
self.pod.append(Widget())
inventory.widgets_inv.pop()

在您的原始代码中,您始终创建一个新的库存对象,因此它具有空的小部件列表:
Inventory().widgets_inv.pop()

关于python-3.x - 在 Python 中更改另一个类中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44892845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com