I have a template that looks something like this:
class Foobar(object):
This allows Foo and Bar to accept either a new value (to create a Foobar ) or an existing instance of Foobar as an argument to Foobar .
I would like to get rid of this redundant code:
# ... if isinstance(foobar, Foobar): self.foobar = foobar else: self.foobar = Foobar(foobar)
I reviewed the following, but this does not work due to infinite recursion in Foobar.__new__() :
class Foobar(object): def __new__(cls, value): if isinstance(value, cls): return value else: return Foobar(value) def __init__(self, value): self.value = value class Foo(object): def __init__(self, value, foobar) self.value = value self.foobar = Foobar(foobar) class Bar(object): def __init__(self, value, foobar) self.value = value self.foobar = Foobar(foobar)
What is the best way to let classes create new instances or use existing instances depending on the values passed to __init__ ?
source share