Home > Blockchain >  Class in another class, the error as TypeError: Student.__init__() missing 1 required positional arg
Class in another class, the error as TypeError: Student.__init__() missing 1 required positional arg

Time:09-03

class Student:

    def __init__(self,name,rollno,lap):
        self.name=name
        self.rollno=rollno
        self.lap=self.laptop()
        

    def show(self):
        print(s1.name,s1.rollno)

    class laptop:

        def __init__(self):
            self.brand="HP"
            self.CPU="i9"
            self.RAM="8gb"

    

s1=Student('raj',2)
s2=Student("raju",3)


s1.show()


lap1=s1.lap
lap1=s2.lap

CodePudding user response:

Your class requires 3 arguments name,rollno,lap when you call the class it's only providing 2. if you want to make lap optional, you can make it a keyword argument like lap=0 then it wont be required when you initiate the class.

Or in your case I think you may just want to take lap out of the __init__ arguments

CodePudding user response:

class Stud:

def __init__(self,name,rollno,lap):
    self.name=name
    self.rollno=rollno
    self.lap=self.laptop()

def show(self):
    print(self.name,self.rollno)
    self.lap.show()

class laptop:

    def __init__(self):
        self.brand="HP"
        self.CPU="i5"
        self.RAM=8

    def show(self):
        print(self.brand,self.CPU,self.RAM)
lap1=Stud.laptop()

#l1=Stud('raj',2,Stud.laptop())

l1=Stud('raj',2,lap1)

#l2=Stud('raju',3,Stud.laptop())

l2=Stud('raju',3,lap2)

print(l1.name, l1.rollno)
print(l2.name, l2.rollno)

print(l1.show())

print(lap1.brand)
print(lap1.CPU)
print(lap1.RAM)

these are the outputs:

raj 2

raju 3

raj 2

HP i5 8

None

HP

i5

8

CodePudding user response:

I found the answer after breaking my head last night and learned many things from this example:

class Stud:
    def __init__(self,name,rollno,lap):
        self.name=name
        self.rollno=rollno
        self.lap=self.laptop()

    def show(self):
        print(self.name,self.rollno)
        self.lap.show()

    class laptop:
        def __init__(self):
            self.brand="HP"
            self.CPU="i5"
            self.RAM=8

        def show(self):
            print(self.brand,self.CPU,self.RAM)

lap1=Stud.laptop()
#l1=Stud('raj',2,Stud.laptop())
l1=Stud('raj',2,lap1)
#l2=Stud('raju',3,Stud.laptop())
l2=Stud('raju',3,lap2)

print(l1.name, l1.rollno)
print(l2.name, l2.rollno)

print(l1.show())

print(lap1.brand)
print(lap1.CPU)
print(lap1.RAM)

Output:

raj 2
raju 3
raj 2
HP i5 8
None
HP
i5
8
  • Related