Where am I going wrong with this problem? I get the error - TypeError: init() missing 2 required positional arguments: 'm' and 'n'
class hello:
def __init__(self, m,n):
self.g = m
self.h = n
def hi(self, x, y):
a = x g
b = x h
return a,b
m = 100
n = 200
obj = hello()
c = obj.hi(10,11)
print(c)
CodePudding user response:
Because you have not provided the positional arguments while constructing your class also there is a bug in the hi function, you have to pass m and n to the hello object when constructing as a positional arguments
class hello:
def __init__(self, m, n): #this needs m and n
self.g = m
self.h = n
def hi(self, x, y):
a = x self.g
b = x self.h #use self to access other class members
return a, b
m = 100
n = 200
obj = hello(m, n) #pass m and n to the constructor
c = obj.hi(10, 11)
print(c)
CodePudding user response:
When you are have parameters in your constructor, you cannot initialize an object without passing arguments i.e
class A:
def __init__(self,a):
self.a=a
# Creating an instance of the class
a=A(3)# Here you have to pass the argument as the constructor cannot reference any default value
print(a.a)# 3
# If you don't want to pass any argument you can pass default arguments i.e
class B:
def __init__(self,b=2)
self.b=b
# Instantiating class B
b = B() # this will not get any error as it will pick the default value you've provided in the constructor
print(b.b)# 2
# If you want to capture all
class C:
def __init__(self,a,*args,**kwargs):
self.a=a
self.args=args
self.kwargs=kwargs
# In the C class args will pick all the arguments passed after a is provided and the kwargs will pick the key value pair arguments provided if any
