修改属性的首选方法

2024-10-05 10:35:19 发布

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

我在我的类中使用一个helper方法来修改一个属性,并且可以看到几种方法来做到这一点。以下任何一种helper和相关的methods是出于合理的理由而被首选还是避免

class Test(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def _x_helper1(self):
        self.x += self.y

    def method1(self):
        # some other code...
        self._x_helper1()

    def _x_helper2(self, y):
        # some other code...
        self.x += y

    def method2(self):
        # some other code...
        self._x_helper2(self.y)

    def _x_helper3(self, y):
        # some other code...
        return y

    def method3(self):
        # some other code...
        self.x += self._x_helper3(self.y)

Tags: 方法testselfhelper属性defcodesome
1条回答
网友
1楼 · 发布于 2024-10-05 10:35:19

这个例子太抽象了

添加obj.x + obj.y没有什么错。如果您需要改变对象的状态,并且只根据属性改变,请使用

def mutate(self):
    self.x += self.y

相关问题 更多 >

    热门问题