所以我是新手,我一直在努力遵循DRY原则。
所以我有一个班级
class Player(object):
lifecondition = True
hitpoints = 100
def __init__(self, name):
self.name = name
def death(self):
self.lifecondition = False
列表
playerlist = ["Player1", "Player2", "Player3", "Player4", "Player5",
"Player6", "Player7", "Player8", "Player9", "Player10"]
和一个功能
def addplayers(alist):
for item in alist:
item = Player("%s" % item)
print "%s has %s HP of life and feels pretty much alive" % (item.name, item.hitpoints, )
我通过函数
向对象添加对象addplayers(playerlist)
到目前为止一切都很好,但如果我做了
print Player1.name
我收到Player1没有定义。我错过了什么?
答案 0 :(得分:0)
你可能应该这样做:
def addplayers(alist):
players = []
for item in alist:
# NOTE reuse the name item is not a good idea here. You can use player instead.
item = Player("%s" % item)
players.append(item)
print "%s has %s HP of life and feels pretty much alive" % (item.name, item.hitpoints, )
return players
并用
调用它players = addplayers(playerlist)
print(players[0])
最后一点不是关于你的问题,但最好将你的班级定义为
class Player(object):
def __init__(self, name):
self.name = name
self.lifecondition = True
self.hitpoints = 100
def death(self):
self.lifecondition = False
因为您可能希望每个玩家都有不同的hitpoints
。请参阅有关类变量和实例变量here的Python文档。