2013-03-02 96 views
0
randomState = collections.namedtuple('randomState', ['player', 'score']) 

比方说,我有一个包含播放器/得分namedtuple如果我是来取代任何的这些功能,我会做:Python类和替换函数?

def random(state): 
    return state._replace(score='123') 

如何创建具有的功能,基本上类类似于一个namedtuple,并且能够手动替换任一玩家/分数?

class Random: 
    def abc(self, score): 
     if self.score == '123': 
      ###had it were a namedtuple, I would use the replace function here, but classes don't allow me to do that so how would I replace 'score' manually? 

我不知道如果我在这里做的意义,但如果有人明白我的问题,我更感谢您的反馈。谢谢

回答

1

如果我的问题得到解决,您需要一个函数,根据分数的值赋予它一些新的值。 这是你在找什么?

# recommended to use object as ancestor 
class randomState(object): 
    def __init__(self, player, score): 
     self.player = player 
     self.score = score 

    def random(self, opt_arg1, opt_arg2): 
     # you may want to customize what you compare score to 
     if self.score == opt_arg1: 
      # you may also want to customize what it replaces score with 
      self.score = opt_arg2 

实施例:

my_state = randomState('David', '100') 
new_state = my_state.random('100', '200') 
+0

OMG。非常感谢。我不敢相信我没有想到这一点。 – Kara 2013-03-02 11:03:49