如何在 Python3 中将参数传递给具有相同对象的内部 class 外部和内部 classes?

How to pass arguments to inner class with same object for Outer and Inner classes in Python3?

下面的代码在我为外部和内部 类 分别创建对象并传递参数的情况下运行良好

class Student:
    def __init__(self,name,rollno):
        self.name = name
        self.rollno = rollno
    def show(self):
        print(self.name,self.rollno)
        #self.lap.show()

    class Laptop: #inner class
        def __init__(self,brand,cpu'):
            self.brand = brand
            self.cpu = cpu
        def show(self):
            print(self.brand,self.cpu)
s1 = Student('Ram',21)
lap1 =s1.Laptop('Dell','i3')
lap1.show()

In the second code, I have created the inner class(Laptop) object inside the Outer(Student) class. In that case, how can we pass the arguments to the inner class?

class Student:
    def __init__(self,name,rollno):
        self.name = name
        self.rollno = rollno
        self.lap = self.Laptop()  #lap is the obj of a inner class

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

I tried with self.lap = self.Laptop(brand,cpu), assigning parameters and passing the arguments in differnet ways, but none worked for me. Is there any way where I can pass the arguments?

我真的看不到内部 class 的额外好处。我见过很少的用例,它们实际上有助于提高代码的可读性。在您的代码中,我建议只使用两个 'top level' classes。只有在一些复杂的情况下,内部 classes 才真正有用。

class Student:
    def __init__(self, name, rollno, laptop=None):
        self.name = name
        self.rollno = rollno
        self.laptop = laptop

    def show(self):
        print(self.name, self.rollno)
        if self.laptop:
            self.laptop.show()

class Laptop:
    def __init__(self, brand, cpu):
        self.brand = brand
        self.cpu = cpu

    def show(self):
        print(self.brand, self.cpu)

然后在使用中,只需初始化并根据需要传递它们:

lap1 = Laptop('Dell', 'i3')
s1 = Student('Ram', 21, lap1)
lap1.show()
s1.show()
s2 = Student('Whosebug', 9999, lap1)
s2.show()
s3 = Student('No laptop', 2)
s3.show()

如果您真的希望 Laptop class 包含在 Student class 中,要么将参数传递给 Student 构造函数,要么将 self.lap = self.Laptop() 替换为self.lap = None。这样你就不需要在创建学生时担心这些参数,以后可以像第一个例子一样将笔记本电脑分配给学生。

class Student:
    def __init__(self,name,rollno):
        self.name = name
        self.rollno = rollno
        self.lap = None  #lap is the obj of a inner class

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

    class Laptop: #inner class
        def __init__(self,brand,cpu):
            self.brand = brand
            self.cpu = cpu
        def show(self):
            print(self.brand,self.cpu)

s1 = Student('Ram',21)
lap1 =s1.Laptop('Dell','i3')
lap1.show()