我正在解析一个文本文件并在文本文件中每行创建一个对象。 在解析每一行时,我创建了一个时间戳,我想将其与对象本身一起返回给调用代码。
我意识到并且目前正在通过将时间戳存储在对象本身并在创建对象后访问它来实现这一点,但我发现如果我可以在创建对象时返回 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)
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/