gpt4 book ai didi

python - python中的构造函数链接

转载 作者:太空狗 更新时间:2023-10-30 00:26:58 24 4
gpt4 key购买 nike

我的类中有两个构造函数:

def __init__(self):
self(8)

def __init__(self, size):
self.buffer = [1] * size

我希望第一个构造函数以默认大小调用第二个构造函数。这在 python 中可以实现吗?

最佳答案

您不能在 Python 中定义多个初始化器(如注释中所指出的,__init__ is not really a constructor ),但您可以定义默认值,例如:

def __init__(self, size=8):
self.buffer = [1] * size

在上面的代码中,默认创建一个大小为 8 的缓冲区,但如果指定了大小参数,则会使用该参数代替。

例如,假设初始值设定项位于名为 Example 的类中。此调用将创建该类的一个新实例,其缓冲区大小为 8(默认值):

e = Example()

鉴于此调用将创建一个缓冲区大小为 10 的新实例:

e = Example(10)

或者,您也可以这样调用构造函数:

e = Example(size=10)

关于python - python中的构造函数链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8376758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com