2010-11-24 29 views

回答

1

child1.MethodA()將被調用。大多數動態語言中的方法基本上總是虛擬的,因爲在運行時查找self

+0

它不是這裏重要的虛擬。如果您在C++中嘗試相同的操作並且MethodA爲虛擬,則將調用Parent :: MethodA。 – 2010-11-24 20:10:28

3

試試看:

class Parent(object): 
    def __init__(self, params): 
     self.method(params) 

    def method(self, params): 
     print "Parent's method called with", params 

class Child(Parent): 
    def method(self, params): 
     print "Child's method called with", params 

Child('foo') 

輸出:調用FOO

孩子的方法

+0

+1用於修復代碼並在方法中添加self – amccormack 2010-11-24 20:09:22

0

Python中所有方法都是虛。

>>> class Parent(object): 
     def __init__(self): 
      self.MethodA() 

    def MethodA(self): 
      print 'A method' 

>>> class child1(Parent): 
    def MethodA(self): 
      print 'child1 method' 

>>> x = child1() 
child1 method 
>>> x.MethodA() 
child1 method 
相關問題