假设我有一个包含多个字符类信息的键和值字典,例如: 'knight'或'mage',我想将它们应用于玩家对象以确定其属性。
class Player(Object):
CHARCLASSDICT = {'knight': {'level': 4, 'health': 50, 'stamina': 50, 'mana': 50,
'strength': 10, 'defense': 8, 'intelligence': 8}}
def __init__(self):
self.name = 'Unknown'
self.charclass = 'Traveller'
self.level = 1
self.health = 1
self.stamina = 1
self.mana = 1
self.strength = 1
self.defense = 1
self.intelligence = 1
player = Player()
使用这些值,我希望用户向我提供他们希望成为的类的字符串,并将值从dict传输到播放器对象。
inp = raw_input('What class would you like to be?: ').lower()
if inp == 'knight':
# Apply stats from self.CHARCLASSDICT['warrior'] to the player object's init function attributes.
我怎么能这样做?
答案 0 :(得分:0)
如何将player_type
传递给__init__()
方法?
代码 -
class Player(object):
CHARCLASSDICT = {'knight': {'level': 4,
'health': 50,
'stamina': 50,
'mana': 50,
'strength': 10,
'defense': 8,
'intelligence': 8}}
def __init__(self, player_type):
self.name = 'Unknown'
self.charclass = 'Traveller'
self.level = self.CHARCLASSDICT[player_type]['level']
self.health = self.CHARCLASSDICT[player_type]['health']
self.stamina = self.CHARCLASSDICT[player_type]['stamina']
self.mana = self.CHARCLASSDICT[player_type]['mana']
self.strength = self.CHARCLASSDICT[player_type]['strength']
self.defense = self.CHARCLASSDICT[player_type]['defense']
self.intelligence = self.CHARCLASSDICT[player_type]['intelligence']
player_type = raw_input('What type of player? : ')
player = Player(player_type)