1

In a situation like this b1 and b2 both have the same instanse of A.

class A:
    def __init__(self):
        self.var=1

class B:
    a=A()
    def __init__(self):
        pass

b1=B()
b2=B()
b1.a.var=2 #changing "var" in b1 would also change it in b2
print(b2.a.var) # prints 2 

What should i do to have 2 different instances of A in B?

Stals
  • 1,543
  • 4
  • 27
  • 52

4 Answers4

6

With B defined as it is, its attribute a belongs to the class itself, not each individual instance. You would need to do something like this:

class B:
    def __init__(self):
        self.a = A()

to get separate instances of A for every B.

multipleinterfaces
  • 8,913
  • 4
  • 30
  • 34
2

You need to initialize it on a per-instance basis instead of at the class level like you have now:

class B:
    def __init__(self):
        self.a = A()
Daniel DiPaolo
  • 55,313
  • 14
  • 116
  • 115
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
2

You were using what amounts to a static variable. Try this:

class A:
    def __init__(self):
        self.var = 1

class B:
    def __init__(self):
        self.a = A()
Chris Eberle
  • 47,994
  • 12
  • 82
  • 119
2

You're initialising A() as a static class variable when it is first parsed. To have one instance of A() per instance of B() it should be in the __init__ of B()

class A:
    def __init__(self):
        self.var=1
class B:
    def __init__(self):
        self.a = A()

b1=B()
b2=B()
b1.a.var=2 # changing "var" in b1 would not change it in b2
print(b2.a.var) # now prints 1
Stals
  • 1,543
  • 4
  • 27
  • 52
Paystey
  • 3,287
  • 2
  • 18
  • 32