当我的类包含默认的init方法和Python中的更多参数时,会出现错误 [英] Getting error when my class contains init method with default and with more parameters in Python

查看:77
本文介绍了当我的类包含默认的init方法和Python中的更多参数时,会出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,



我在类中定义了两个init方法,就像我在代码片段中提到的那样



现在我们使用这个课程



它给出了错误



追溯(大多数)最近的呼叫最后一次):

文件,第20行,在< module>

employee = Employee()

TypeError:__ init __()缺失1个必要的位置参数:'workingHrs'






我的问题是,如何使用和不使用init方法参数除了'self'参数



我尝试过:



  class 员工:
def __init __(self):
print ' 这是init方法'

def __init __(self,workingHr s):
print ' 这是带参数'的init方法)

employee = Employee()
employee = Employee( 1

解决方案

Python不支持多个构造函数(__init__)

您可以使用可选参数和拆分功能创建一个。 。

  class 员工:
def __init __(self,workingHrs = ):
如果 workingHrs
print ' 这是init方法'
else
print ' 这是带参数')的初始方法


In Python,

I defined two init methods inside a class as I mentioned in the code snippet

Now when we use this class

It gives error

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



My question is, how can I use both init method with and without parameter except 'self' parameter

What I have tried:

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)

解决方案

Python does not support multiple constructors (__init__)
You can create one with optional parameter and split functionality...

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


这篇关于当我的类包含默认的init方法和Python中的更多参数时,会出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆