通过whileloop创建对象而不使用列表?

2024-06-16 15:34:21 发布

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

我是Python新手,我对这种语言有点了解。 是否可以使用while循环创建多个对象? 我想给对象一个相同的名称+数字,比如:wuff = "object"+count或者什么

第一个是:object1

2cnd:object2

等等

这是可能的,还是我必须使用列表

课程为:

class Animal:
    def __init__(self,name,alter,typ):
        self.typ = typ
        self.name = name
        self.alter = alter

代码:

count = int(input("Enter amount of Inputs: "))

try:
    while count>0:
        wuff = Animal(input("Enter Name: "), input("Enter Age: "), input("Enter Type: "))

>         wuff = "object"+count

        count-=1
except ValueError:
    print("Wrong input!")

print(wuff.name, wuff.alter, wuff.typ)

Tags: 对象nameself语言inputobjectcountprint
1条回答
网友
1楼 · 发布于 2024-06-16 15:34:21

我是否可以建议一种不使用列表的解决方案:

鉴于您的类具有结构:

class Animal:
    def __init__(self,name,alter,typ):
        self.typ = typ
        self.name = name
        self.alter = alter

在主代码中,您可以进行一些更改,以便不需要使用列表,即将类更改为:

class Animal:
    def __init__(self):
        self.typ = None
        self.name = None
        self.alter = None

这基本上允许您在声明类对象时不必设置其属性就可以声明它。 因此,随着类结构的更改,您的主代码,即此代码:

count = int(input("Enter amount of Inputs: "))

try:
    while count>0:
        wuff = Animal(input("Enter Name: "), input("Enter Age: "), input("Enter Type: "))

          wuff = "object" + count

        count-=1
except ValueError:
    print("Wrong input!")

print(wuff.name, wuff.alter, wuff.typ)

我们可以将其更改为以下代码:

count = int(input("Enter amount of Inputs: "))
wuff = Animal()
try:

    while count > 0:
        wuff.name = str(input("Enter Name: "))
        wuff.alter = int(input("Enter Age: ")) # assuming that you mean to set age by the attr. alter
        wuff.typ = str(input("Enter Type: "))
        # wuff = "object" + count # removed the line because it is incorrect
        # The code line was removed tries to add a string literal with an integer.
        count -= 1

except ValueError:
    print("Wrong input!")

print(wuff.name, wuff.alter, wuff.typ)

为了创建多个对象,您需要有多个标识符。 因此,您需要使用某种形式的存储方法,即某种列表或字典。因此,要做到这一点:

class Animal:
    def __init__(self,name,alter,typ):
        self.typ = typ
        self.name = name
        self.alter = alter

count = int(input("Enter amount of Inputs: "))
objectDict = {}

try:
    while count > 0:

        Name = str(input("Enter Name: "))
        Alter = int(input("Enter Age: ")) 
        Typ = str(input("Enter Type: "))
        
        objectDict[Name] = Animal(Name, Alter, Typ)
        count -= 1

except ValueError:
    print("Wrong input!")

print(wuff.name, wuff.alter, wuff.typ)

我希望这是有用的

通过使用SQL DB存储对象并以属性和内容表的形式存储对象,可以避免列表(尽管不推荐)和内容

我希望这个答案令人满意

相关问题 更多 >