2013-03-02 86 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