[英]How to create instances of a class based on user input with a while loop
我试图根据用户输入创建某个类的实例,并显示其属性,这是我的代码:
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”
我相信您正在尝试从member_of_team类创建一个对象。 然后,您将对象的名称作为输入,然后尝试访问该对象的属性。
您可以使用Python的getattr()内置函数。
getattr(object,name [,默认])
返回对象的命名属性的值。 名称必须是字符串。 如果字符串是对象属性之一的名称,则结果是该属性的值。 例如,getattr(x,'foobar')等同于x.foobar。 如果指定的属性不存在,则返回默认值(如果提供),否则引发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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.