Met this case when tried to parse some string data into a recursive data structure, and had a counter to be passed through.
Python does not allow to return anything from __init__
, but you may write a factory function, or a class method, or a Parser
class, depending on the code structure and complexity of parsing, which will parse your data into data objects.
Global variable is not a good solution, as it may be changed somewhere else, breaking the parsing logic.
Function example:
class MyClass():
def __init__(self, a, b, c):
# only assignments here
self.a = a
self.b = b
self.c = c
# return None
def parse(data):
# parsing here
a = ...
b = ...
c = ...
# status, counter, etc.
i = ...
# create an object
my_obj = MyClass(a, b, c)
# return both
return my_obj, i
# get data and parse
data = ...
my_obj, i = parse(data)
Class method example:
class MyClass():
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
@classmethod
def parse(cls, data):
a = ...
b = ...
c = ...
i = ...
obj = cls(a, b, c)
return obj, i
data = ...
my_obj, i = MyClass.parse(data)