简体   繁体   English

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

[英]how to assign Class Instance to a variable and use that in other class

I am doing some basic practice for Python.我正在为 Python 做一些基本练习。 Here, I am defining 3 classes.在这里,我定义了 3 个类。 Now, I need to pass instance of first class in another class and use that in the last one.现在,我需要在另一个类中传递第一类的实例并在最后一个类中使用它。

I wrote code like below:我写了如下代码:

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

The above i giving error 'NameError: name 'm' is not defined' for test_add_new_stock_as_dict method.上面我为 test_add_new_stock_as_dict 方法给出了错误“NameError: name 'm' is not defined'。

Why is it not taking m, when I am declaring that in class?当我在课堂上宣布时,为什么不带 m? how is it possible to use MobileInventory.balance_inventory directly in add_stock class?如何在 add_stock 类中直接使用 MobileInventory.balance_inventory? I tried it's giving error.我试过它给出错误。

Expected: I need to remove the NameError.预期:我需要删除 NameError。 And any way to use MobileInventory.balance_inventory (ie another class reference) directly in class without instance of that以及在没有实例的情况下直接在类中使用 MobileInventory.balance_inventory(即另一个类引用)的任何方式

Python variable name scopes prefer the local scope over anything outside, so you need to tell the interpreter where m is coming from. Python 变量名范围更喜欢本地范围而不是外部范围,因此您需要告诉解释器m来自哪里。

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

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

AND for Testing this use this library from proj.inventory import MobileInventory, InsufficientException import pytest并且为了测试这个使用这个库 from proj.inventory import MobileInventory, InsufficientException import pytest

class TestingInventoryCreation():类 TestingInventoryCreation():

def test_creating_empty_inventory(self):
    c1 = MobileInventory()
    assert c1.balance_inventory == {}

def test_creating_specified_inventory(self):
    c2 = MobileInventory({'iPhone Model X':100, 'Xiaomi Model Y': 1000, 'Nokia Model Z':25})
    assert c2.balance_inventory == {'iPhone Model X':100, 'Xiaomi Model Y': 1000, 'Nokia Model Z':25}
    #{'iPhone Model X':100, 'Xiaomi Model Y': 1000, 'Nokia Model Z':25}

def test_creating_inventory_with_list(self):
    #c3 = MobileInventory(['iPhone Model X', 'Xiaomi Model Y', 'Nokia Model Z'])
    with pytest.raises(TypeError) :
        c3 = MobileInventory(['iPhone Model X', 'Xiaomi Model Y', 'Nokia Model Z'])


def test_creating_inventory_with_numeric_keys(self):
    #c4 = MobileInventory({1:'iPhone Model X', 2:'Xiaomi Model Y', 3:'Nokia Model Z'})
    with pytest.raises(ValueError):
        c4 = MobileInventory({1:'iPhone Model X', 2:'Xiaomi Model Y', 3:'Nokia Model Z'})


def test_creating_inventory_with_nonnumeric_values(self):
    #c5 = MobileInventory({'iPhone Model X':'100', 'Xiaomi Model Y': '1000', 'Nokia Model Z':'25'})
    with pytest.raises(ValueError):
        c5 = MobileInventory({'iPhone Model X':'100', 'Xiaomi Model Y': '1000', 'Nokia Model Z':'25'})


def test_creating_inventory_with_negative_value(self):
    #c6 = MobileInventory({'iPhone Model X':-45, 'Xiaomi Model Y': 200, 'Nokia Model Z':25})
    with pytest.raises(ValueError) :
        c6 = MobileInventory({'iPhone Model X':-45, 'Xiaomi Model Y': 200, 'Nokia Model Z':25})

class TestInventoryAddStock(): inventory = None类 TestInventoryAddStock(): 库存 = 无

    @classmethod
    def setup_class(cls):
            cls.inventory = MobileInventory({'iPhone Model X': 100, 'Xiaomi Model Y': 1000, 'Nokia Model Z':25})

    def test_add_new_stock_as_dict(self):
            self.inventory.add_stock({'iPhone Model X': 50, 'Xiaomi Model Y': 2000, 'Nokia Model A': 10})
            assert self.inventory.balance_inventory == {'iPhone Model X': 150, 'Xiaomi Model Y': 3000, 'Nokia Model Z': 25, 'Nokia Model A': 10}


    def test_add_new_stock_as_list(self):
            with pytest.raises(TypeError) :
                    MobileInventory.add_stock(['iPhone Model X', 'Xiaomi Model Y', 'Nokia Model Z'])


    def test_add_new_stock_with_numeric_keys(self):
            with pytest.raises(ValueError):
                    MobileInventory.add_stock({1:'iPhone Model A', 2:'Xiaomi Model B', 3:'Nokia Model C'})


    def test_add_new_stock_with_nonnumeric_values(self):
            with pytest.raises(ValueError):
                    MobileInventory.add_stock({'iPhone Model A':'50', 'Xiaomi Model B': '2000', 'Nokia ModelC':'25'})


    def test_add_new_stock_with_float_values(self):
            with pytest.raises(ValueError):
                    MobileInventory.add_stock({'iPhone Model A':50.5, 'Xiaomi Model B':2000.3, 'Nokia Model C':25})

class TestInventorySellStock(): inventory = None类 TestInventorySellStock(): 库存 = 无

@classmethod
def setup_class(cls):
    cls.inventory = MobileInventory(
        {'iPhone Model A': 50, 'Xiaomi Model B': 2000, 'Nokia Model C': 10, 'Sony Model D': 1})

def test_sell_stock_as_dict(self):
    self.inventory.sell_stock({'iPhone Model A': 2, 'Xiaomi Model B': 20, 'Sony Model D': 1})
    assert self.inventory.balance_inventory == {'iPhone Model A': 48, 'Xiaomi Model B': 1980, 'Nokia Model C': 10,
                                                'Sony Model D': 0}

def test_sell_stock_as_list(self):
    with pytest.raises(TypeError):
        MobileInventory.sell_stock(['iPhone Model A', 'Xiaomi Model B', 'Nokia Model C'])

def test_sell_stock_with_numeric_keys(self):
    with pytest.raises(ValueError):
        MobileInventory.sell_stock({1: 'iPhone Model A', 2: 'Xiaomi Model B', 3: 'Nokia Model C'})

def test_sell_stock_with_nonnumeric_values(self):
    with pytest.raises(ValueError):
        MobileInventory.sell_stock({'iPhone Model A': '5', 'Xiaomi Model B': '3', 'Nokia Model C': '4'})

def test_sell_stock_with_float_values(self):
    with pytest.raises(ValueError):
        MobileInventory.sell_stock({'iPhone Model A': 2.5, 'Xiaomi Model B': 3.1, 'Nokia Model C': 4})

def test_sell_stock_of_nonexisting_model(self):
    with pytest.raises(InsufficientException):
        MobileInventory.sell_stock({'iPhone Model B': 2, 'Xiaomi Model B': 5})

def test_sell_stock_of_insufficient_stock(self):
    with pytest.raises(InsufficientException):
        MobileInventory.sell_stock({'iPhone Model A': 2, 'Xiaomi Model B': 5, 'Nokia Model C': 15})
def test_sell_stock_of_nonexisting_model(self):
    with pytest.raises(InsufficientException):
        MobileInventory.sell_stock({'iPhone Model B': 2, 'Xiaomi Model B': 5})

def test_sell_stock_of_insufficient_stock(self):
    with pytest.raises(InsufficientException):
        MobileInventory.sell_stock({'iPhone Model A': 2, 'Xiaomi Model B': 5, 'Nokia Model C': 15})

TypeError: sell_stock() missing 1 required positional argument: 'requested_stock'类型错误:sell_stock() 缺少 1 个必需的位置参数:'requested_stock'

I guess below is the expected way of defining the class attribute while running the Pytests.我猜下面是在运行 Pytests 时定义类属性的预期方式。

class TestInventoryAddStock:
    @classmethod
    def setup_class(cls):
        cls.inventory = MobileInventory({'iPhone Model X':100, 'Xiaomi Model Y': 1000, 'Nokia Model Z':25})

    
    def test_add_new_stock_as_dict(self):
        self.inventory.add_stock({'iPhone Model X':50, 'Xiaomi Model Y': 2000, 'Nokia Model A':10})
        assert self.inventory.balance_inventory == {'iPhone Model X':150, 'Xiaomi Model Y': 3000, 'Nokia Model Z':25, 'Nokia Model A':10}
class InsufficientException(Exception):
    pass


class MobileInventory:
    balance_inventory = {}
    def __init__(self, inventory=None):
        if not inventory:
            MobileInventory.balance_inventory = {}
        else:
            if 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")
            else:
                for i in inventory.values():
                    if isinstance(i, int) and i > 0:
                        pass
                    else:
                        raise ValueError("No. of mobiles must be a positive integer")
            MobileInventory.balance_inventory = inventory

@classmethod
def add_stock(cls, new_stock):
    print("before update")
    print(cls.balance_inventory)
    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")
    else:
        for i in new_stock.values():
            if isinstance(i, int) and i > 0:
                pass
            else:
                raise ValueError("No. of mobiles must be a positive integer")

    for key, value in new_stock.items():
        if key in cls.balance_inventory.keys():
            x = cls.balance_inventory[key] + value
            cls.balance_inventory[key] = x
        else:
            cls.balance_inventory.update({key: value})
    print(new_stock)
    print("after update")
    print(cls.balance_inventory)


@classmethod
def sell_stock(cls, requested_stock):
    if not isinstance(requested_stock, dict):
        raise TypeError("Requested stock must be a dictionary")
    elif not (set(map(type, requested_stock)) == {str}):
        raise ValueError("Mobile model name must be a string")
    else:
        for i in requested_stock.values():
            if isinstance(i, int) and i > 0:
                pass
            else:
                raise ValueError("No. of mobiles must be a positive integer")
    for key, value in requested_stock.items():
        if key in cls.balance_inventory.keys():
            if cls.balance_inventory[key] < value:
                raise InsufficientException("Insufficient Stock")
            else:
                y = cls.balance_inventory[key] - value
                cls.balance_inventory[key] = y
        else:
            raise InsufficientException("No Stock. New Model Request")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何为类实例变量赋值? - How to assign a value to a class instance variable? 将模块方法分配给Class变量或Instance变量 - Assign module method to a Class variable or Instance variable 如何在 class 中获取和使用实例变量? - How to take and use an instance variable in a class? 如何创建实例变量并在类内部使用? - How to create instance variable and use inside the class? Python - 将类变量指针分配给实例方法 - Python - assign class variable pointer to instance method 如何在Class中定义带有值的变量以及如何在其他Class中使用 - How define variable with value inside Class and how to use in other Class 当我对两个不同的类使用一个基本 class 并更改一个 class 实例中的变量时,另一个 class 实例中的变量也会更改吗? - When I use one base class for two different classes, and change a variable within one class instance, the variable in the other class is also changed? 共享给其他实例的类中的全局变量 - Global variable in class shared to other instance WxPython - 如何通过其他类访问类实例 - WxPython - How to acces class instance by other class 将类实例变量分配给Python方法中的局部变量 - Assign a class instance variable to a local variable within a method in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM