如何将类实例分配给变量并在其他类中使用它 [英] how to assign Class Instance to a variable and use that in other class

查看:51
本文介绍了如何将类实例分配给变量并在其他类中使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 Python 做一些基本的练习.在这里,我定义了 3 个类.现在,我需要在另一个类中传递第一个类的实例并在最后一个类中使用它.

I am doing some basic practice for Python. Here, I am defining 3 classes. Now, I need to pass instance of first class in another class and use that in the last one.

我写的代码如下:

#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'.

The above i giving error 'NameError: name 'm' is not defined' for test_add_new_stock_as_dict method.

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

Why is it not taking m, when I am declaring that in class? how is it possible to use MobileInventory.balance_inventory directly in add_stock class? I tried it's giving error.

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

Expected: I need to remove the NameError. And any way to use MobileInventory.balance_inventory (i.e. another class reference) directly in class without instance of that

推荐答案

Python 变量名作用域更喜欢局部作用域而不是外部作用域,因此您需要告诉解释器 m 来自何处.

Python variable name scopes prefer the local scope over anything outside, so you need to tell the interpreter where m is coming from.

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

Both in the first and second method, you can use Test_Inventory_Add_Stock.m to refer to your static class variable 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})

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

But that doesn't look very good. To keep the variables confined to an instance of the class, try this:

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()

这篇关于如何将类实例分配给变量并在其他类中使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆