搜尋

首頁  >  問答  >  主體

python - 多型呼叫方法時卻顯示bound method...

class Programer(object):

hobby='play computer'

def __init__(self,name,age,weight):
    self.name=name
    self._age=age
    self.__weight=weight

def self_intro(self):
    print 'my name is %s \nI am %s years old\n' % (self.name, self._age)

class BackendProgramer(Programer):

def __init__(self,name,age,weight,language):
    super(BackendProgramer,self).__init__(name,age,weight)
    self.language = language

def self_intro(self):
    print 'my name is %s \nmy favourite language is %s\n' % (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 <>

<bound method BackendProgramer.self_intro of <>

<bound method BackendProgramer.self_intro of <lt;

<bound method BackendProgramer.self_intro of <lt;__b.Back ;### ###請問為什麼運行結果不是my name is ...###
怪我咯怪我咯2748 天前937

全部回覆(1)我來回復

  • 伊谢尔伦

    伊谢尔伦2017-06-12 09:27:43

    因為你忘了呼叫了

    def intro(f):
        if isinstance(f,Programer):
            print f.self_intro()   # 没有()只是函数对象而已, 加了()才是调用

    回覆
    0
  • 取消回覆