sam2611
sam2611

Reputation: 455

How can I pass parameters to the class in python

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()

Upvotes: 0

Views: 7111

Answers (1)

Wild Zyzop
Wild Zyzop

Reputation: 620

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

Upvotes: 3

Related Questions