Python面向对象设计;返回,设置实例变量或两者

时间:2010-08-11 20:42:35

标签: python oop object

好的我有一些代码可以归结为像这样的模式

class Foo(object):
def get_something1(self):
    # in the actual code it asks a web server but here I replaced that with "foo_something1" instead of the code from a web server
    self.something1 = "foo_something1"

def get_something2(self):
    # needs the result of get_something1; right now I have it get it by instance variable like so
    self.something2 = self.something1 + "_something_2"

我的问题是,我是否应该执行上述操作(通过实例变量获取所需的方法)或采用类似的参数;我应该在get_ *方法中返回something1和something2吗?

class Foo(object):
def get_something1(self):
    # in the actual code it asks a web server but here I replaced that with "foo_something1" instead of the code from a web server
    self.something1 = "foo_something1"

def get_something2(self, something_1):
    # needs the result of get_something1; right now I have it get it by instance variable like so
    self.something2 = something1 + "_something_2"

现在在我的代码中,方法返回deferreds(twisted);现在,当deferreds触发时,它设置实例变量并返回None;在实际的代码中,我有另一个函数来检查something1或something2是否过期;我更新它们会带来一个问题,因为我更新了它......

d = self.get_something1()
##d.addCallback(self.get_something2) # errors because it gets the argument None (so I do below)
d.addCallback(lambda ignored: self.get_something2())# problem the deferred for get_something2 is inaccessible

现在,更新代码要么是丑陋的,要么是错误的,要么两者兼而有之。所以我有一种感觉,我做的事情要么a)非pythonic或b)un twisted或c)其他一些糟糕的设计。


感谢您的回答,但这些不起作用,因为函数返回延迟而不是实际值(否则它必须阻止)。

1 个答案:

答案 0 :(得分:4)

不要使用get_*方法。在Python中,更好的方法是使用属性:

class Foo(object):
    @property
    def something1(self):
        # in the actual code it asks a web server but here I replaced that with "foo_something1" instead of the code from a web server
        return "foo_something1"
    @property
    def something2(self):
        # needs the result of get_something1; right now I have it get it by instance variable like so
        return self.something1 + "_something_2"

请注意,当something1是属性时,self.something1(没有括号!)会调用相应的函数Foo.something1

使用代码后,您可以看到something2的使用方式。如果你有两个

    @property
    def something2(self):
        return self.something1 + "_something_2"

    @property
    def something3(self):
        return self.otherthing1 + "_something_2"

然后您可能想要重构代码以使用

    def something2(self,prefix):
        return prefix+"_something_2"

我们对你的情况了解不多,告诉你哪个更好。但是,一旦看到工作代码的使用模式,答案就会变得很明显。