Python类和替换函数?
假设我有一个包含player/score的namedtuple,如果我要替换其中任何一个函数,我会:Python类和替换函数?,python,Python,假设我有一个包含player/score的namedtuple,如果我要替换其中任何一个函数,我会: randomState = collections.namedtuple('randomState', ['player', 'score']) 如何创建一个类,该类的函数基本上类似于namedtuple,并且能够手动替换任一player/score def random(state): return state._replace(score='123') 我不确定我在这里是否讲得通
randomState = collections.namedtuple('randomState', ['player', 'score'])
如何创建一个类,该类的函数基本上类似于namedtuple,并且能够手动替换任一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?
例如:
# 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')