如何使用while循环基于用户输入创建类的实例

时间:2018-08-26 06:17:01

标签: python

我试图根据用户输入创建特定类的实例,并显示其属性,这是我的代码:

class member_of_team:
   def __init__(self, outside_shot, inside_shot, handling, speed):
        self.outside_shot = outside_shot
        self.inside_shot = inside_shot
        self.handling = handling
        self.speed = speed          

choice = input("Would you like to enter a teamate? ")
y = choice
while  y == "yes":

    x = input("what is the teamates name? ")
    a = int(input("How good is he at shooting outside? "))
    b = int(input("What about his inside shot? "))
    c = int(input("How well is he at handling the ball? "))
    d = int(input("How fast is he? "))
    x = member_of_team(a, b, c, d)
    y = input("Do you want to enter another teamate? ")

r = input("what member of the team woulsd you like to check up")
s = input("what would you like ot know about him")

print(r.s)

AttributeError:'str'对象没有属性's'

1 个答案:

答案 0 :(得分:0)

我相信您正在尝试从 member_of_team 类创建对象。然后,您将对象的名称作为输入,然后尝试访问该对象的属性。

您可以使用Python的 getattr()内置函数。

  

getattr(对象,名称[,默认])

     

返回已命名的值   对象的属性。名称必须是字符串。如果字符串是名称   对象的其中一个属性之一,结果就是该值   属性。例如,getattr(x,'foobar')等效于   x.foobar。如果named属性不存在,则返回默认值   如果提供,则引发AttributeError。

因此,您需要维护所有创建对象的目录。因为在python中是动态创建对象的。并且当您从STDIN提供对象的名称时。您可以通过String的形式获得它。您实际上需要找出其等效的OOP对象。

请查看此代码。

class member_of_team(object):
   def __init__(self, outside_shot, inside_shot, handling, speed):
        self.outside_shot = outside_shot
        self.inside_shot = inside_shot
        self.handling = handling
        self.speed = speed

choice = input("Would you like to enter a teamate? ")
object_directory = {}

while  choice == "yes":
    x1 = input("what is the teamates name? ")
    a = int(input("How good is he at shooting outside? "))
    b = int(input("What about his inside shot? "))
    c = int(input("How well is he at handling the ball? "))
    d = int(input("How fast is he? "))
    x = member_of_team(a, b, c, d)
    object_directory[x1] = x
    y = input("Do you want to enter another teammate? ")

r = input("what member of the team would you like to check up?")
s = input("what would you like to know about him?")


print (getattr(object_directory[r], s))

示例控制台输出:

Would you like to enter a teamate? yes
what is the teamates name? Ronaldo
How good is he at shooting outside? 5
What about his inside shot? 7
How well is he at handling the ball? 8
How fast is he? 8
Do you want to enter another teammate? no
what member of the team would you like to check up?Ronaldo
what would you like ot know about him?handling
8