0

I have tried to create a class inside a class, How to pass parameters? Here is my code , can someone help me correct this code:

class student:
 def __init__(self, name, rollno, brand, ram, cpu):
 self.name = name
 self.rollno = rollno
 self.lap = self.laptop(self, brand, ram)
 def show(self):
 print(self.name, self.rollno)
 class laptop:
 def __init__(self, brand, ram, cpu):
 self.brand = brand
 self.ram = ram
 self.cpu = cpu
 def show(self):
 print(self.brand,self.ram,self.cpu)
 def __str__(self):
 return self.brand, self.ram, self.cpu
 def __str__(self):
 return self.name, self.rollno
 s1=student("Raj",3,"hp","i5",16)
 s2=student("Ram", 2, "dell", "i3", 8)
 
 s1.show()
asked Jun 29, 2021 at 9:14

1 Answer 1

3

You must pass the parameters of the internal class through the constructor of the external class:

class student:
 def __init__(self, name, rollno, brand, ram, cpu):
 self.name = name
 self.rollno = rollno
 self.lap = self.laptop(brand, ram, cpu)
 def show(self):
 print(self.name, self.rollno)
 self.lap.show()
 class laptop:
 def __init__(self, brand, ram, cpu):
 self.brand = brand
 self.ram = ram
 self.cpu = cpu
 def show(self):
 print(self.brand, self.brand, self.cpu)

Result:

>>> s1=student("Raj",3,"hp","i5",16)
>>> s1.show()
Raj 3
hp hp 16
>>> s2=student("Ram", 2, "dell", "i3", 8)
>>> s2.show()
Ram 2
dell dell 8
answered Jun 29, 2021 at 9:29
Sign up to request clarification or add additional context in comments.

2 Comments

No , I am still unable to pass parameter to the variable like brand, ram and cpu.
@sam2611 have you added variables to the student class constructor def __init__(self, name, rollno, brand, ram, cpu): and to the laptop class constructor call self.lap = self.laptop(brand, ram, cpu)?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.