python - 获取 python 对象以在创建时返回多个值,包括 self

标签 python python-2.7

我正在解析一个文本文件并在文本文件中每行创建一个对象。 在解析每一行时,我创建了一个时间戳,我想将其与对象本身一起返回给调用代码。

我意识到并且目前正在通过将时间戳存储在对象本身并在创建对象后访问它来实现这一点,但我发现如果我可以在创建对象时返回 self 和时间戳对我来说更方便。

我有一个关于如何做到这一点的建议,但我想知道这是否被认为是好的,如果不是,我该如何正确地做到这一点?

class Foo():
    def __init__(self, infile):
        self.time_stamp = foobar(infile)
        self.line = barfoo(infile)

        return (self, self.time_stamp)

(obj, time_stamp) = Foo()

干杯。

最佳答案

can't return anything but None from __init__ :

As a special constraint on constructors, no value may be returned; doing so will cause a TypeError to be raised at runtime.

使用工厂函数:

def create_foo(infile):
    foo = Foo(infile)
    return foo, foo.time_stamp

...

obj, ts = create_foo(a_file)

static method

class Foo(object):
    ...
    @staticmethod:
    def create(infile):
        obj = Foo(infile)

        return obj, obj.time_stamp

...

obj, ts = Foo.create(a_file)

或者,如果您需要它在子类上正常工作,一个 class method

class Foo(object):
    ...
    @classmethod
    def create(cls, infile):
        obj = cls(infile)

        return obj, obj.time_stamp

...

obj, ts = Foo.create(a_file)

当然,这是最简单的方式:

class Foo(object):
    def __init__(self, infile):
        self.time_stamp = ...


obj = Foo(a_file)
ts = obj.time_stamp

我认为摆脱这条额外的生产线并不能保证设计工厂。

关于python - 获取 python 对象以在创建时返回多个值,包括 self,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15878501/

相关文章:

python - 根据我给定的列表获取行,而无需修改顺序或唯一列表

python - django AbstractUser模型 'str'对象没有属性 '_meta'

python - 在列表中查找邻居的最有效方法

python - 如何将具有更多条目的 SQLite 数据库压缩为更小的文件大小?

python - 打印 estimator.predict 张量的问题

python - 重复 os.path.isdir 调用中的巨大内存泄漏?

python - pyodbc 不报告 sql server 错误

Python Pyfolio PYMC3 ValueError

python - 如何为python应用创建多阶段dockerfile?

python - EAFP样式的错误消息