在初始化器中使用对象方法(同一行) [英] Use an object method with the Initializer (Same line)

查看:46
本文介绍了在初始化器中使用对象方法(同一行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在清理python对象类,主要关注如何创建对象. __ init __ 方法创建一个空字典,几乎需要立即将其填充.但这不应该在 __ init __ 内发生,因为所使用的方法会千差万别.这是一个示例:

I'm cleaning up a python object class, focusing mainly on how the object is created. The __init__ method creates a an empty dictionary that needs to be filled almost instantly. But this should NOT happen within the __init__, as the method used will vary widely. Here's an example:

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

通常,我可以像这样一个接一个地打电话:

Normally, I can just call one after the other like so:

box = Storage.Storage()
box.fill_1()

但是,当我顺序创建许多这些对象时,这可能会令人不知所措.我的目标是将 __ init __ 方法与同一行上的 fill 方法之一一起使用.我尝试使用下面的通话:

However, this can be overwhelming when I create many of these objects sequentially. My goal is to use the __init__ method with one of the fill methods on the same line. I've tried using the call below:

box = Storage.Storage().fill_1()

但这不会创建对象,而是返回 None .所以我有两个问题:

But this does not create the object and instead returns None. So I have two questions:

我的代码是否因为行正在调用实例方法而返回 None 对象?

Is my code returning a None object because the line is calling an instance method?

又如何创建 Storage 对象,然后在同一行中调用它的 fill 方法?

And how can I create the Storage object and then call it's fill method within the same line?

推荐答案

这不是一个成语,您在python中经常会看到(虽然在许多其他语言中特别流行,尤其是javascript),但是您可以通过以下方式来做到这一点从mutator函数返回 self .(似乎您也缺少实例方法的 self 参数).这意味着您还可以链接mutator调用- Storage().fill_1().fill_2()

This is not an idiom you tend to see that often in python (though it's quite prevalent in many other languages, especially javascript), but you could do this by returning self from the mutator functions. (It looks like you were missing the self argument to the instance methods as well). This means you could also chain mutator calls -- 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()

这篇关于在初始化器中使用对象方法(同一行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆