我正在清理一个 python 对象类,主要关注对象的创建方式。 __init__
方法创建了一个需要立即填充的空字典。但这不应该发生在 __init__
中,因为使用的方法会有很大差异。这是一个例子:
class Storage:
def __init__(self):
self.data = {}
def fill_1(self):
self.data['solo'] = 'all alone'
def fill_2(self, buddy, bff):
self.data['buddy'] = buddy
self.data['bff'] = bff
def fill_3(self, that_guy, house):
self.data[that_guy] = house
通常,我可以像这样一个接一个地调用:
box = Storage.Storage()
box.fill_1()
但是,当我按顺序创建许多这样的对象时,这可能会让人不知所措。我的目标是在同一行中使用 __init__
方法和其中一个 fill
方法。我试过使用下面的调用:
box = Storage.Storage().fill_1()
但这不会创建对象,而是返回 None
。所以我有两个问题:
我的代码是否因为调用实例方法而返回了一个None对象?
我如何创建 Storage
对象,然后在同一行中调用它的 fill
方法?
最佳答案
这不是您在 Python 中经常看到的习语(尽管它在许多其他语言中非常普遍,尤其是 JavaScript),但您可以通过从 mutator 函数返回 self
来做到这一点。 (看起来您也缺少实例方法的 self
参数)。这意味着您还可以链接修改器调用——Storage().fill_1().fill_2()
class Storage(object):
def __init__(self):
super(Storage, self).__init__()
data = {}
def fill_1(self):
data['solo'] = 'all alone'
return self
def fill_2(self, buddy, bff):
data['buddy'] = buddy
data['bff'] = bff
return self
def fill_3(self, that_guy, house):
data[that_guy] = house
return self
box = Storage().fill_1()
关于python - 使用带有 Initializer 的对象方法(同一行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36484000/