python - Getting an error when my class contains two __init__ method with default and more parameters -


i defined 2 __init__ methods inside class mentioned in code snippet

class employee:    def __init__(self):       print('this init method')     def __init__(self, workinghrs):       print('this init method parameter') 

now when use class

employee = employee() employee = employee(1) 

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 use both __init__ methods , without parameter except self parameter.

python doesn't support method overloading when 2 methods have same name second 1 replace first one.

this can solved using optional argument:

class employee(object):    def __init__(self, workinghrs=none):       if workinghrs none:           print('this init method')       else:           print('this init method parameter') 

you use classmethods "implement" different constructors.


Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -