2016-02-23 79 views

回答

1

成員的基類只是提供給子類,以及(除非它們被覆蓋):

class Base: 
    def example (self): 
     print('This is in the base class') 

class Subclass (Base): 
    def test (self): 
     self.example() 

Subclass類型的對象,現在可以直接訪問example或間接:

>>> x = Subclass() 
>>> x.test() 
This is in the base class 
>>> x.example() 
This is in the base class 
1
class Parent(object): 
    def __init__(self, name): 
     self.name = name 
    def output(self): 
     print self.name 



class Child(Parent): 
    def __init__(self, name, age): 
     Parent.__init__(self, name) 
     self.age = age 

    def output(self): 
     super(Child, self).output() 
     print self.age 


if __name__ == '__main__': 
    a = Parent("wy") 
    b = Child("zhang", 10) 
    a.output() 
    b.output() 

你可以試試這個代碼。