简体   繁体   English

在另一个类构造函数中实例化一个类的唯一实例

[英]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? 概述不应该在每次实例化时创建一个新的Details()实例吗?

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

# 2940786890344
# 2940786890344

The default argument to details is evaluated at class creation time! 默认的details参数在类创建时进行评估! All instances of Overview will have the identical Details instance if not provided. 如果未提供,则Overview所有实例将具有相同的Details实例。 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 . 对于初学者来说,这是一个普遍的惊喜,特别是在使用可变的默认参数的情况下

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM