gpt4 book ai didi

python - 当我的类包含两个带有默认参数和更多参数的 __init__ 方法时出现错误

转载 作者:行者123 更新时间:2023-11-28 18:19:57 25 4
gpt4 key购买 nike

正如我在代码片段中提到的,我在一个类中定义了两个 __init__ 方法

class Employee:
def __init__(self):
print('This is init method')

def __init__(self, workingHrs):
print('This is init method with parameter')

现在我们使用这个类

employee = Employee()
employee = Employee(1)

它给出了这个错误:

Traceback (most recent call last):
File, line 20, in <module>
employee = Employee()
TypeError: __init__() missing 1 required positional argument: 'workingHrs'

我的问题是,除了 self 参数外,我如何使用带参数和不带参数的 __init__ 方法。

最佳答案

Python 不支持 method overloading因此,当两个方法具有相同的名称时,第二个将替换第一个。

这可以通过使用可选参数来解决:

class Employee(object):
def __init__(self, workingHrs=None):
if workingHrs is None:
print('This is init method')
else:
print('This is init method with parameter')

您还可以使用 classmethod 来“实现”不同的构造函数。

关于python - 当我的类包含两个带有默认参数和更多参数的 __init__ 方法时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45695700/

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