【问题标题】:calling class with user input使用用户输入调用类
【发布时间】:2016-09-14 21:47:14
【问题描述】:

我对@9​​87654322@ 和编程非常陌生。我试图创建一个小程序,告诉你 NFL 球队的四分卫。我让它开始工作,但我想看看是否有一种重复性较低的方法,原因有两个:

  • 这样我就不必输入那么多了,并且
  • 因为它会使我的代码更短。

我试图让用户输入插入到类调用中,这样我就不必输入太多并使用很多 elif 命令,例如:

x= input("")`
print (x.qb,x.num)

这是我目前所拥有的。它现在有效,但我想要一种更简单的方法来完成它:

class football:
    def __init__(self,qb,num):                                                                                         
        self.qb = qb
        self.num = num

Niners = football("Gabbert", "02" )
Bears = football("CUTLER, JAY","06") 
Bengals = football ("Dalton, Andy","14")
Bills =football (" Taylor, Tyrod", "05")
Broncos =football ("Sanchez, Mark", "06")
Browns =football ("MCCOWN, JOSH", "13")
Bucaneers =football ("Winston, Jameis", "03")
Cardinals =football ("PALMER, CARSON", "03")
Chargers =football ("RIVERS, PHILIP", "17")
Cheifs =football ("SMITH, ALEX", '11')
Colts =football ("Luck, Andrew",' 12' )
Cowboys =football ("Romo,Tony","09")
Dolphins =football ("Tannehill, Ryan", '17' )
Eagles =football ("Bradford, Sam", '07')
Falcons =football ("RYAN, MATT",' 02' )
Giants =football ("MANNING, ELI", '10' )
Jaguars =football ("Bortles, Blake", '05')
Jets =football ("Smith, Geno",' 07' )
Lions =football ("Stafford, Matthew", '09' )
Packers =football ("RODGERS, AARON", '12')
Panthers =football ("Newton, Cam",' 01' )
Patriots =football ("BRADY, TOM", '12')
Raiders =football ("Carr, Derek",' 04')
Rams =football ("Foles, Nick", '05')
Ravens =football ("FLACCO, JOE",' 05')
Redskins =football ("Cousins, Kirk", '08')
Saints =football ("BREES, DREW",' 09' )
Seahawks =football ("Wilson, Russell", '03')
Steelers =football ("ROETHLISBERGER, BEN",' 07')
Texans =football ("Osweiler, Brock", '17')
Titans =football ("Mariota, Marcus",' 08' ) 
Vikings=football ("Bridgewater, Teddy", '05' )

def decor(func):
    def wrap():
        print("===============================")
        func()
        print("===============================")
    return wrap

def print_text():
    print("Who\s your NFL Quarterback? ")

decorated = decor(print_text)
decorated()

team= input(" Enter your teams name here:").lower()

if team == "cowboys":
    print (Cowboys.qb,Cowboys.num) 
elif team == "niners":
    print (Niners.qb,Niners.num)

【问题讨论】:

  • 我认为字典是这里更合适的数据结构。
  • 好的,我会阅读那些我所说的对这一切都很陌生的东西。事实上,这是我制作的第一个小程序。
  • 我觉得这个问题更适合Code Review

标签: class python-3.x methods


【解决方案1】:

一个不错的选择是使用字典来引用football 的每个实例,这样可以避免最后出现大量的ifelif 结构:

class football:
    def __init__(self,qb,num):
        self.qb = qb
        self.num = num

    def __str__(self):
        return self.qb + ", " + self.num
teams = {
"Niners" : football("Gabbert", "02" ),
"Bears" : football("CUTLER, JAY","06"),
"Bengals" : football ("Dalton, Andy","14"),
"Bills" : football (" Taylor, Tyrod", "05")} #etc
#I didn't include the whole dictionary for brevity's sake

def decor(func):
    def wrap():
        print("===============================")
        func()
        print("===============================")
    return wrap

def print_text():
    print("Who\s your NFL Quarterback? ")

decorated = decor(print_text)
decorated()

team = input("Enter your teams name here:").capitalize()
print(teams[team])

您会注意到团队现在位于字典中,因此可以通过使用团队名称索引字典轻松访问每个团队的 football 实例。这就是在语句 print(teams[team]) 的最后一行所做的。

teams[team] 返回与存储在team 中的键关联的值。例如,如果用户输入Chiefs,则字符串'Chiefs' 将存储在team 中。然后,当您尝试使用teams[team] 索引字典时,它会访问'Chiefs' 的字典条目。

但请注意,从teams[team] 返回的是一个football 对象。通常,当您只打印一个对象时,它会打印一些看起来有点像here 的内容,因为它只是打印有关该对象的一些原始信息。让它返回你想要的方法是在类中定义一个__repr____str__ 方法(有关here 的更多信息)。这正是我在football 类中所做的,因此当打印该类的实例时,它将以所需的格式打印所需的信息。


另一种方法是完全取消该类,而只使用一个字典,其值是包含四分卫姓名及其编号作为元素的元组。代码看起来有点像这样:

teams = {
"Niners" : ("Gabbert", "02" ),
"Bears" : ("CUTLER, JAY","06"),
"Bengals" : ("Dalton, Andy","14"),
"Bills" : (" Taylor, Tyrod", "05")} #etc
# Again, not including the whole dictionary for brevity's sake

def decor(func):
    def wrap():
        print("===============================")
        func()
        print("===============================")
    return wrap

def print_text():
    print("Who\s your NFL Quarterback? ")

decorated = decor(print_text)
decorated()

team = input("Enter your teams name here:").capitalize()
print(teams[team][0], teams[team][1])

这次teams[team] 是一个元组。最后一行是打印第一个元素(四分卫的名字),然后是第二个元素(数字)。


第二个更简洁,需要的代码更少,但这确实是个人喜好问题。

docs中有更多关于字典的信息。

此外,为了简洁起见,我缩短了代码示例,但您可以在 pastebin 上查看完整的代码示例。

【讨论】:

  • 哦,哇,非常感谢 Xamuel Schulman,我真的很感激,而且信息量很大,我开始做第二个,在阅读本文之前没有意识到我可以将它们留在 (),尽管他们不得不再次感谢我正在寻找的东西。
  • 是的,我是这个网站/应用程序的新手,我是否可以通过左侧的检查来做到这一点
  • @JesseHinojosa 是的。非常感谢。
猜你喜欢
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
  • 2020-08-17
  • 2011-11-04
  • 2022-12-03
  • 2021-11-19
  • 2019-08-06
  • 2019-05-03
相关资源
最近更新 更多