Python:如何根据用户输入打印对象属性

时间:2019-12-06 12:43:10

标签: python input

目标:我想根据用户输入从类中返回一个属性。

具体地说,我为足球俱乐部创建了一个类,并添加了一些团队。我想问用户他最喜欢的球队是什么,然后打印他最喜欢的球队的属性,例如该球队的最佳球员。

因此,如果用户输入“ Liverpool”,则需要将我的fotballclub类中的答案与“ Liverpool”进行匹配,并返回bestplayer属性。

类似的东西:

class Club:

    def __init__(self, name, kitcolor, bestplayer):
        self.name = name
        self.kitcolor = kitcolor
        self.bestplayer = bestplayer

Liverpool = Club("Liverpool", "red", "Salah")
Chelsea = Club("Chelsea", "blue", "Azpilicueta")

favorite_team = input("What is your favorite team in Premier League?")

EXAMPLE print("The best player of your favorite team is " + Liverpool.bestplayer)

任何想法,将不胜感激,谢谢。

2 个答案:

答案 0 :(得分:0)

一种简单的方法是将实例放入字典中

name2club = {}

# create Clubs

name2club[Liverpool.name] = Liverpool
name2club[Chelsea.club] = Chelsea

favorite_team = input("What is your favorite team in Premier League?")

print(f"The best player of your favorite team is {name2club[favorite_team].bestplayer}.")

如果字典是class属性,则可能会更方便:

class Club:

    name2club = {}

    def __init__(self, name, kitcolor, bestplayer):
        self.name = name
        self.kitcolor = kitcolor
        self.bestplayer = bestplayer
        self.name2club[name] = self

Liverpool = Club("Liverpool", "red", "Salah")
Chelsea = Club("Chelsea", "blue", "Azpilicueta")

favorite_team = input("What is your favorite team in Premier League?")
print(f"The best player of your favorite team is {Club.name2club[favorite_team].bestplayer}.")

答案 1 :(得分:0)

您可以使用eval在运行时获取对象。 当对象不存在时,将引发“ NameError”错误。

class Club:

    def __init__(self, name, kitcolor, bestplayer):
        self.name = name
        self.kitcolor = kitcolor
        self.bestplayer = bestplayer

Liverpool = Club("Liverpool", "red", "Salah")
Chelsea = Club("Chelsea", "blue", "Azpilicueta")

favorite_team = input("What is your favorite team in Premier League?")
try:
  print("The best player of your favorite team is " + eval(favorite_team).bestplayer)
except NameError:
  print(favorite_team + " data not in this program")