烦!!! 发表于 2020-8-15 11:01:28

运行不了

class Turtle:
    def __init__(self,x):
      self.num = x

class Fish:
    def __init__(self,x):
      self.num = x

class Pool:
    def __init__(self,x,y):
      self,turtle = Turtle(x)
      self.fish = Fish(y)

class print_num(self):
    print('水池里总共有乌龟 %d 只,小鱼 %d 条!' %(self.turtle.num, self.fish.num))

Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\面向对象(3).py", line 16, in <module>
    class print_num(self):
NameError: name 'self' is not defined

sunrise085 发表于 2020-8-15 11:04:39

本帖最后由 sunrise085 于 2020-8-15 11:06 编辑

class print_num(self):
    print('水池里总共有乌龟 %d 只,小鱼 %d 条!' %(self.turtle.num, self.fish.num))
这里写错了不应该是class,应该是def。他是Pool类的函数,不是一个新的类
def print_num(self):
    print('水池里总共有乌龟 %d 只,小鱼 %d 条!' %(self.turtle.num, self.fish.num))

另外
class Pool:
    def __init__(self,x,y):
      self,turtle = Turtle(x)
      self.fish = Fish(y)
第三行写错了。应该是self.turtle = Turtle(x),你把 . 写成 , 了

烦!!! 发表于 2020-8-15 11:12:07

sunrise085 发表于 2020-8-15 11:04
这里写错了不应该是class,应该是def。他是Pool类的函数,不是一个新的类




我该配副眼镜了,捂脸~
页: [1]
查看完整版本: 运行不了