python - 多态调用方法时却显示bound method...
问题描述
class Programer(object):
hobby=’play computer’def __init__(self,name,age,weight): self.name=name self._age=age self.__weight=weightdef self_intro(self): print ’my name is %s nI am %s years oldn’ % (self.name, self._age)
class BackendProgramer(Programer):
def __init__(self,name,age,weight,language): super(BackendProgramer,self).__init__(name,age,weight) self.language = languagedef self_intro(self): print ’my name is %s nmy favourite language is %sn’ % (self.name, self.language)
def intro(f):
if isinstance(f,Programer): print f.self_intro
if __name__==’__main__’:
prog = Programer(’Albert’,25,’80’)back_prog = BackendProgramer(’Alex’,23,’80’,’Ruby’)intro(prog)intro(back_prog)
运行结果是:<bound method Programer.self_intro of <__main__.Programer object at 0x02505330>><bound method BackendProgramer.self_intro of <__main__.BackendProgramer object at 0x02505370>>
请问为什么运行结果不是my name is ...
问题解答
回答1:因为你忘记调用了
def intro(f): if isinstance(f,Programer):print f.self_intro() # 没有()只是函数对象而已, 加了()才是调用
相关文章: