nven
nven

Reputation: 1207

Instantiate unique instances of a class in another class constructor

I have two classes. One which instantiates the other in its constructor.

class Details(object):
    pass

class Overview(object):
    def __init__(self, details = Details()):
        self.details = details

When I create two instances of overview, they change the same instance of details. Shouldn't Overview create a new instance of Details() upon every instantiation?

ov1 = Overview()
ov2 = Overview()
print(id(ov1.details))
print(id(ov2.details))

# 2940786890344
# 2940786890344

Upvotes: 0

Views: 83

Answers (1)

user2390182
user2390182

Reputation: 73470

The default argument to details is evaluated at class creation time! All instances of Overview will have the identical Details instance if not provided. Change along the lines of:

class Overview(object):
    def __init__(self, details=None):
        self.details = Details() if details is None else details

This is a common source of surprise for beginners, especially with mutable default arguments.

Upvotes: 2

Related Questions