单选题
适中
#16949
执行下面代码,将输出( )。 class Instrument: def play(self): print("乐器在演奏声音") def __del__(se…
执行下面代码,将输出( )。
class Instrument:
def play(self):
print("乐器在演奏声音")
def __del__(self):
pass
class Piano(Instrument):
def play(self):
print("钢琴:叮咚叮咚")
class Guitar(Instrument):
def play(self):
print("吉他:咚咚当当")
if __name__ == "__main__":
instruments = [Piano(), Guitar()]
for inst in instruments:
Instrument.play(inst)
答案与解析
正确答案:B
解析
分析类的继承关系和方法重写机制。确定Instrument类中play方法被Piano和Guitar类各自重写。观察列表instruments中存储的是子类实例。遍历该列表时,通过inst获取每个对象,但调用的是父类Instrument的play方法,并将inst作为参数传入。该调用方式绕过子类的play方法,直接执行父类版本。需理解显式使用类名调用实例方法时,不会触发动态绑定,而是执行指定类中的方法实现。