0
randomState = collections.namedtuple('randomState', ['player', 'score'])

假设我有一个包含 player/score 的 namedtuple,如果我要替换这些函数中的任何一个,我会这样做:

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

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

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? 

我不确定我在这里是否有意义,但如果有人理解我的问题,我将非常感谢您的反馈。谢谢

4

1 回答 1

1

If I get your question right, you need a function which, depending on score's value assigns some new value to it. Is it what you are looking for?

# 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

Example:

my_state = randomState('David', '100')
new_state = my_state.random('100', '200')
于 2013-03-02T10:49:41.320 回答