G. *_*ews 4 attributes class python-3.x
我一直在尝试从类 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()
Run Code Online (Sandbox Code Playgroud)
您应该修改creat_pod方法,以便您可以移交 Inventory 对象。这允许您在调用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()
Run Code Online (Sandbox Code Playgroud)
在您的原始代码中,您始终创建一个新的库存对象,因此它具有空的小部件列表:
Inventory().widgets_inv.pop()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
844 次 |
最近记录: |