访问类的值

2024-06-28 11:08:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用用户输入来获取对象属性的值。 我尝试了一些方法,但没有达到目标

class Product:
    def __init__(self, name, n, t, parts):
        self.name = name
        self.n = n         
        self.t = t                  
        self.parts = parts                      


SensorCase = Product("Case", 7, 10, ("Bodenplatte", "Mikrocontroller", "Deckel"))

x = input("Name of the Object! ")
print(getattr(inpt, 'x'))

它应该是这样的:用户键入对象的名称(大小写) python将所需属性的值打印出来(n=7)

提前谢谢你


Tags: 对象方法用户nameself属性initdef
1条回答
网友
1楼 · 发布于 2024-06-28 11:08:20

假设您要维护一个产品列表,并根据用户输入的名称在列表中搜索匹配项,那么这应该可以让您开始:

class Product:
    def __init__(self, name, n, t, parts):
        self.name = name
        self.n = n         
        self.t = t                  
        self.parts = parts                      

all_product = [
    Product("Case", 7, 10, ("Bodenplatte", "Mikrocontroller", "Deckel")),
    Product("Fan", 7, 10, ("Bodenplatte", "Mikrocontroller", "Deckel")),
    Product("Footing", 7, 10, ("Bodenplatte", "Mikrocontroller", "Deckel")),
    Product("Widget", 7, 10, ("Bodenplatte", "Mikrocontroller", "Deckel"))
]

product_name = input("Enter product name: ")

for product in all_product:
    if product.name == product_name:
        print("{} : {}".format(product.name, product.n))
        break
else:
    print("no matching products found.")

最终,我认为您将希望在一个更适合搜索的结构中维护产品集合,例如dict,但这将让您现在开始

相关问题 更多 >