创建内部类的实例

2024-06-25 23:12:40 发布

您现在位置: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'

我知道这是一个极其基本的问题,但我无法在网上找到解决办法


Tags: nameselfinitdefshowcpuclassram
1条回答
网友
1楼 · 发布于 2024-06-25 23:12:40

只是不要把params放在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()

 

相关问题 更多 >