书上第11章,11.6 组合
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)
def print_num(self):
print('水池里共有乌龟 %d 只,小鱼 %d 条' % (self.turtle, self.fish))
pool = Pool(1, 10)
pool.print_num()
按照书上敲的代码,但是最后结果报错:
AttributeError: 'Pool' object has no attribute 'print_num' 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)
def print_num(self):
print('水池里共有乌龟 %d 只,小鱼 %d 条' % (self.turtle, self.fish)) #改了这里,你这里缩进不对!
pool = Pool(1, 10)
pool.print_num()
问题1:你 print_num 方法没放入 Pool 类中,导致调用此方法报错,将缩进打上即可
问题2:Pool 类中的 self.turtle 和 self.fish 的赋值为 Turtle(x),Fish(y) 均为实例对象,而 print_num 格式化打印时候,应该打印 self.turtle.num 和 self.fish.num
参考代码:
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)
def print_num(self):
print('水池里共有乌龟 %d 只,小鱼 %d 条' % (self.turtle.num, self.fish.num))
pool = Pool(1, 10)
pool.print_num() python爱好者. 发表于 2022-5-4 17:07
非常感谢!改了的那行,self.turtle, self.fish这两个后边还要加.num Twilight6 发表于 2022-5-4 17:25
问题1:你 print_num 方法没放入 Pool 类中,导致调用此方法报错,将缩进打上即可
问题2:Pool 类中 ...
谢谢大佬
页:
[1]