Python类和替换功能?

时间:2013-03-02 10:29:34

标签: python

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

假设我有一个包含播放器/分数的命名元组,如果我要替换任何这些函数,我会这样做:

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? 

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

1 个答案:

答案 0 :(得分: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')