2322312 发表于 2016-11-21 10:38:11

python 之简单聊聊 类的继承

#_*_coding:utf-8 _*_

#父类
class Father:
    def __init__(self):
      self.Fname = 'fffffff'
    def Func(self):
      print 'funcfurnc'
    def Bar(self):
      print 'barbarbar'
    def Test(self): #再定义一个方法
      print '11111'
      print 'testtest'

#子类继承父类,也就是说Son类可以拿到Father类的方法
class Son(Father):
    def __init__(self):
      self.Sname = 'sonsonson'
    def Yes(self):
      print 'barbarbar'
    def Test(self):
      print 'aaaaaaaa'    #重写父类的Test方法

#实例化子类,尝试访问在父类的方法
s1 = Son() #实例化子类
s1.Bar()    #成功访问父类的方法
s1.Test()   #访问重写后的方法

f1 = Father()
f1.Test()


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#_*_coding:utf-8 _*_

#多重继承
class A(object):
    def __init__(self):
      print 'this is A'
    def save(self):
      print 'save method from A'

class B(A):
    def __init__(self):
      print 'this is B'

class C(A):
    def __init__(self):
      print 'this is C'
    def save(self):
      print 'save method from D'
class D(C,B):
    def __init__(self):
      print 'this is D'

c = D()
c.save()






页: [1]
查看完整版本: python 之简单聊聊 类的继承