从方法更改属性

2024-04-19 19:03:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个筷子游戏。这里有一个维基百科链接到游戏https://en.wikipedia.org/wiki/Chopsticks_(hand_game)。到目前为止,我只是添加了一些方法,以便一只手可以使用“攻击”方法攻击另一只手。我觉得我写的代码非常冗长,丑陋,甚至可能是错误的。我怎样才能写得更优雅呢

class game:
    def __init__(self):
        self.x_left = 1
        self.x_right = 1
        self.o_left = 1
        self.o_right = 1  

    def set_x_left(self, num):
        self.x_left = num

    def set_x_right(self, num):
        self.x_right = num

    def set_o_left(self, num):
        self.o_left = num

    def set_o_right(self, num):
        self.o_right = num    

    def dict_func(self, hand):        
        self.func= {'x_left': self.set_x_left, 'x_right': self.set_x_right,
             'o_left': self.set_o_left, 'o_right': self.set_o_right}

        return self.func[hand]

    def dict_hand(self, hand):
        self.hands = {'x_left': self.x_left, 'x_right': self.x_right,
             'o_left': self.o_left, 'o_right': self.o_right}     

        return self.hands[hand]

    def attack(self, from_hand, to_hand):
        self.dict_func(to_hand)(self.dict_hand(from_hand) + self.dict_hand(to_hand))

Tags: to方法selfrightgame游戏returndef
1条回答
网友
1楼 · 发布于 2024-04-19 19:03:03

您的代码似乎有一些不必要的方法。您可以去掉用数字设置变量的方法:

def set_x_left(self, num):
    self.x_left = num

创建游戏实例时,可以使用点符号设置值:

chopsticks = game()
#   ^^^ that's the instance

chopsticks.set_x_left(0)
# is the same as 
chopsticks.x_left = 0

正如你所看到的,它打字更快,不需要任何方法。只是属性赋值。这样做会影响dict_func方法,因此可以创建匿名函数:

def dict_func(self, hand):        
    self.func = {'x_left': lambda self, x: self.x_left = x,
                 'x_right': lambda self, x: self.x_right = x,
                 'o_left': lambda self, x: self.o_left = x,
                 'o_right': lambda self, x: self.o_right = x}

    return self.func[hand]

实际上,您可以在__init__中声明self.funcself.hands属性,以确保它们只被分配一次。然后在函数中只需写return self.func[hand]

你的dict_hand方法也有点过于复杂。您的目标是从实例dict获取属性,因此可以执行以下操作:

def dict_hand(self, hand):
    return getatttr(self, hand)

(您可能需要重命名此函数:))

相关问题 更多 >