【发布时间】:2019-09-12 15:27:13
【问题描述】:
我正在为 Python 做一些基本的练习。在这里,我定义了 3 个类。 现在,我需要在另一个类中传递第一个类的实例并在最后一个类中使用它。
我写了如下代码:
#defining first class:
class MobileInventory:
def __init__(self, inventory=None):
if inventory == None:
balance_inventory = {}
elif not isinstance(inventory, dict):
raise TypeError("Input inventory must be a dictionary")
elif not (set(map(type, inventory)) == {str}):
raise ValueError("Mobile model name must be a string")
elif [True for i in inventory.values() if (not isinstance(i, int) or i < 1)]:
raise ValueError("No. of mobiles must be a positive integer")
self.balance_inventory = inventory
# class to add elements to existing dictionary of above class
class add_stock:
def __init__(self, m, new_stock):
if not isinstance(new_stock, dict):
raise TypeError("Input stock must be a dictionary")
elif not (set(map(type, new_stock)) == {str}):
raise ValueError("Mobile model name must be a string")
elif [True for i in new_stock.values() if (not isinstance(i, int) or i < 1)]:
raise ValueError("No. of mobiles must be a positive integer")
for key, value in new_stock.items():
if key in m.balance_inventory.keys():
x = m.balance_inventory[key] + value
m.balance_inventory[key] = x
else:
m.balance_inventory.update({key: value})
#class to testing the above functionality
class Test_Inventory_Add_Stock:
m = ''
def setup_class():
m = MobileInventory({'iPhone Model xy': 100, 'Xiaomi Model YA': 1000, 'Nokia Model Zs': 25})
print(m.balance_inventory) # giving Output {'iPhone Model xy': 100, 'Xiaomi Model YA': 1000, 'Nokia Model Zs': 25}
def test_add_new_stock_as_dict():
add_stock( m, {'iPhone Model X': 50, 'Xiaomi Model Y': 2000, 'Nokia Model A': 10})
Test_Inventory_Add_Stock.setup_class()
Test_Inventory_Add_Stock.test_add_new_stock_as_dict()
上面我给 test_add_new_stock_as_dict 方法的错误'NameError: name 'm' is not defined'。
当我在课堂上声明时,为什么不带 m? 如何在 add_stock 类中直接使用 MobileInventory.balance_inventory?我试过它给出错误。
预期: 我需要删除 NameError。 以及直接在类中使用 MobileInventory.balance_inventory(即另一个类引用)的任何方式,而无需实例
【问题讨论】:
-
你得到正确的输出了吗?
标签: python object class-variables