Python 如何将输入数据用作引用现有对象实例的参数?

Python 如何将输入数据用作引用现有对象实例的参数?,python,class,oop,input,Python,Class,Oop,Input,这是我的第一篇stackoverflow文章,我也是一个初学者,所以请原谅我的无知。我一整天都在绞尽脑汁,想弄明白我所想象的是一件简单的事情 我正在开发一个基于面向对象的小程序来查看和修改库存。我一直在尝试从用户获取输入,并将其作为对象参数应用于类方法 简单地说,这就是我试图做的,但它失败了,因为输入的值是一个字符串,该方法需要一个对象名 class_instance.class_method(input()) 更深入。。这是inventory类,您可以看到remove\u product方法

这是我的第一篇stackoverflow文章,我也是一个初学者,所以请原谅我的无知。我一整天都在绞尽脑汁,想弄明白我所想象的是一件简单的事情

我正在开发一个基于面向对象的小程序来查看和修改库存。我一直在尝试从用户获取输入,并将其作为对象参数应用于类方法

简单地说,这就是我试图做的,但它失败了,因为输入的值是一个字符串,该方法需要一个对象名

class_instance.class_method(input())
更深入。。这是inventory类,您可以看到
remove\u product
方法需要一个对象实例

class Inventory(): 

# Instantiate object and give functionality to printing object
def __init__(self):
    self.inventory_summary = {}
    self.inventory_total = 0
    self.products = []

# Remove product objects from inventory and adjust value    
def remove_product(self,product):
    print("\n{} removed from inventory.".format(product.ID))
    self.products.remove(product.ID)
    self.inventory_total -= product.total_value
    del self.inventory_summary[product.ID]
    print("Current inventory of products: {}".format(self.products))
    print("Updated inventory total: ${}".format(self.inventory_total))
在我的应用程序中,我将产品列表显示为字典。当提示从库存中删除产品时,我希望用户能够键入
product1
product类实例的变量名),将
product1
传递给要删除的库存类


这是否可能(且有效/实用/合乎道德)?对任何愿意帮助的人说

> p>您需要某种索引来重新考虑或考虑解析输入字符串。

# Inefficient
def remove_product(self, user_input): 'milk'
   for product in self.products:
       if user_input == product.name:
            ...
你也可以(不要,这很危险)使用eval

def remove_product(self, user_input): # '3'
   product_obj = eval(user_input)() # for 'milk' it would create object of milk class

   # search for your product type and delete

我有点糊涂,所以如果我遗漏了一些非常明显的东西(我读了几遍,但我想我明白了),我会道歉

首先,您的类代码并不是为您想要做的事情而设置的。我在类方面有点困难,所以相信我,我明白了,但以下是您在设置类时如何编写和使用类:

# the class
class Inventory:
# Instantiate object and give functionality to printing object
    def __init__(self, inventory_summary, inventory_total, products):
        self.inventory_summary = inventory_summary
        self.inventory_total = inventory_total
        self.products = products

# The usage
def main():
    summary = {"1":"summary"}
    total = 10
    products = ["products"]
    my_inventory = Inventory(summary, total, products)
    print(my_inventory.inventory_summary)
    print(my_inventory.inventory_total)
    print(my_inventory.products)
输出:

> {'1': 'summary'} 
> 10 
> ['products']
> {}
> 0
> []
但是,听起来您想要创建一个全局类变量,这将像这样实现(比我聪明的人告诉我这样做是错误的,但我仍然使用):

输出:

> {'1': 'summary'} 
> 10 
> ['products']
> {}
> 0
> []
根据我的理解,这应该可以解决你的问题