【问题标题】:Changing attributes from a method call从方法调用更改属性
【发布时间】:2019-02-04 19:13:18
【问题描述】:

我正在尝试制作筷子游戏。这是游戏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))

【问题讨论】:

    标签: python class


    【解决方案1】:

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

    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.func self.hands 属性,以确保它们只被分配一次。然后在函数中你可以写return self.func[hand]

    您的dict_hand 方法也有点过于复杂。您的目标是从实例字典中获取属性,因此您可以这样做:

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

    (你可能想重命名这个函数:))

    【讨论】:

    • 我把它们放进去是为了我的攻击方法。
    • 我认为这实际上行不通。根据我的阅读和遇到的错误,您无法使用 lambda 进行赋值语句。另外,我认为语法可能是错误的。
    • 嗯,我相信你是完全正确的。不知道那件事。但我认为您的 dict_hand 方法应该与 getattr 一起使用
    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2020-10-19
    相关资源
    最近更新 更多