我想创建一个Band
类和一个Musician
类。我正在尝试向Musician
添加Band
。我使用的是Python 2.7.6。
class Band(object):
def __init__(self):
self.members = []
def hire_musician(self,member):
self.members.append(member)
print self.members
class Musician(object):
def __init__(self, sounds,isDrummer):
self.sounds = sounds
self.isDrummer = isDrummer
def solo(self, length):
for i in range(length):
print self.sounds[i % len(self.sounds)],
print ""
class Drummer(Musician):
def __init__(self):
super(Drummer, self).__init__(["Hi", "Hat"],True)
Jingle = Band()
ruben = Drummer()
Jingle.hire_musician(ruben)
我得到的错误是
[<__main__.Drummer object at 0x7fb4785cba10>]
我做错了什么?
答案 0 :(得分:1)
这里只是添加名称属性
的简单解决方案class Band(object):
def __init__(self):
self.members = []
def hire_musician(self,member):
self.members.append(member)
for member in self.members:
print(member.name)
class Musician(object):
def __init__(self, name, sounds,isDrummer):
self.sounds = sounds
self.isDrummer = isDrummer
self.name = name
def solo(self, length):
for i in range(length):
print(self.sounds[i % len(self.sounds)],)
print('')
class Drummer(Musician):
def __init__(self, name):
super(Drummer, self).__init__(name, ["Hi", "Hat"],True)
Jingle = Band()
ruben = Drummer('ruben')
Jingle.hire_musician(ruben)