Initializing object in __init__ parameter list for default value returning same instance
Question:
Given the sample code below:
class Foo:
def __init__(self):
return
class Bar:
def __init__(self, foo = Foo()):
print(foo)
bar1 = Bar()
bar2 = Bar()
print(bar1)
print(bar2)
Outputs the following:
<__main__.Foo object at 0x000002A989A2E9B0>
<__main__.Foo object at 0x000002A989A2E9B0>
<__main__.Bar object at 0x000002A989A2EA20>
<__main__.Bar object at 0x000002A989A2EA90>
It was unexpected that both instances of Foo
were identical. I was hoping that each subsequent creation of a Bar()
object would have it’s own unique version of a Foo
object.
How can I modify my example so that each call to Bar()
will create its own unique version of Foo
? Do I need to use __new__
somehow?
Answers:
class Foo:
pass
class Bar:
def __init__(self, foo = None):
if foo is None:
foo = Foo()
print(foo)
bar1 = Bar()
bar2 = Bar()
print(bar1)
print(bar2)
or
import attr
class Foo:
pass
@attr.s
class Bar(object):
foo = attr.ib(default=attr.Factory(Foo))
bar1 = Bar()
bar2 = Bar()
print(bar1.foo)
print(bar2.foo)
Given the sample code below:
class Foo:
def __init__(self):
return
class Bar:
def __init__(self, foo = Foo()):
print(foo)
bar1 = Bar()
bar2 = Bar()
print(bar1)
print(bar2)
Outputs the following:
<__main__.Foo object at 0x000002A989A2E9B0>
<__main__.Foo object at 0x000002A989A2E9B0>
<__main__.Bar object at 0x000002A989A2EA20>
<__main__.Bar object at 0x000002A989A2EA90>
It was unexpected that both instances of Foo
were identical. I was hoping that each subsequent creation of a Bar()
object would have it’s own unique version of a Foo
object.
How can I modify my example so that each call to Bar()
will create its own unique version of Foo
? Do I need to use __new__
somehow?
class Foo:
pass
class Bar:
def __init__(self, foo = None):
if foo is None:
foo = Foo()
print(foo)
bar1 = Bar()
bar2 = Bar()
print(bar1)
print(bar2)
or
import attr
class Foo:
pass
@attr.s
class Bar(object):
foo = attr.ib(default=attr.Factory(Foo))
bar1 = Bar()
bar2 = Bar()
print(bar1.foo)
print(bar2.foo)