如何将Class Instance分配给变量并在其他类中使用它

问题描述 投票:0回答:1

我正在为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()

上面给出的错误'NameError:name'm'没有为test_add_new_stock_as_dict方法定义。

当我在课堂上宣布时,为什么不接受m?如何在add_stock类中直接使用MobileInventory.balance_inventory?我试过它给出了错误。

预期:我需要删除NameError。以及在没有实例的情况下直接在类中使用MobileInventory.balance_inventory(即另一个类引用)的任何方法

python object class-variables
1个回答
0
投票

Python变量名称范围比外部的任何东西更喜欢本地范围,因此您需要告诉解释器m来自哪里。

在第一种和第二种方法中,您都可以使用Test_Inventory_Add_Stock.m来引用静态类变量m

class Test_Inventory_Add_Stock:

    m = ''

    def setup_class():
        Test_Inventory_Add_Stock.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(Test_Inventory_Add_Stock.m, {'iPhone Model X': 50, 'Xiaomi Model Y': 2000, 'Nokia Model A': 10})

但这看起来不太好。要将变量限制在类的实例中,请尝试以下操作:

class Test_Inventory_Add_Stock:

    def setup_class(self):
        self.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(self):
        add_stock(self.m, {'iPhone Model X': 50, 'Xiaomi Model Y': 2000, 'Nokia Model A': 10})

t = Test_Inventory_Add_Stock()
t.setup_class()
t.test_add_new_stock_as_dict()

© www.soinside.com 2019 - 2024. All rights reserved.