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()
1 Answer 1
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
Wild Zyzop
6301 gold badge5 silver badges14 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
sam2611
No , I am still unable to pass parameter to the variable like brand, ram and cpu.
Wild Zyzop
@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)?lang-py