提问者:小点点

Python中的内在类


class studnt:
    def __init__(self,name,rno):
        self.name = name
        self.rno = rno
        self.laptop = self.laptop()
    
    def show(self):
        print(self.name,self.rno)
        self.laptop.show

    class laptop:

        def __init__(self,brand,cpu,ram):
            self.brand = "ASUS"
            self.cpu = 10
            self.ram = 8  

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

s1 = studnt("rishabh",100)
s2 = studnt("hanuman",1000)

s1.show()

我正在用python学习类,在执行代码时,我得到以下错误

Traceback (most recent call last):
  File "classw.py", line 21, in <module>
    s1 = studnt("rishabh",100)
  File "classw.py", line 5, in __init__
    self.laptop = self.laptop()
TypeError: __init__() missing 3 required positional arguments: 'brand', 'cpu', and 'ram'

我知道这是一个非常基本的问题,但我无法在网上找到解决方案


共1个答案

匿名用户

只要不给laptop的init()方法添加参数,它就会工作:D。

class studnt:
    def __init__(self,name,rno):
        self.name = name
        self.rno = no
        self.laptop = laptop()

    def show(self):
        print(self.name, self.rno)
        self.laptop.show() 

    class laptop:

        def __init__(self):
            self.brand = "ASUS"
            self.cpu = 10
            self.ram = 8  

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

s1 = studnt("rishabh", 100)
s2 = studnt("hanuman", 1000)

s1.show()