简单场景的类继承、复杂场景的类继承(钻石继承)、super、类的方法

1、python子类调用父类成员有2种方法,分别是普通方法和super方法

class Base(object):  #基类的表示方法可以多种,Base(),Base,Base(object),即新式类与经典类
    def __init__(self):
        print('Base create')
class childA(Base):
    def __init__(self):
        print("\n")
        print('creat A ')
        Base.__init__(self) #简单调用父类成员
class childB(Base):
    def __init__(self):
        print("\n")
        print('creat B ')
        super(childB, self).__init__()#super调用父类成员
        #使用super()继承时不用显式引用基类
base = Base()
a = childA()
b = childB()

 

输出:

Base create


creat A 
Base create


creat B 
Base create

2、在子类中重写父类方法,采用super()继承

class FooParent(object):
    def __init__(self):
        self.parent = 'I\'m the parent.'
        print('Parent')
    def bar(self, message):
        print(message, 'from Parent')


class FooChild(FooParent):
    def __init__(self):
        super(FooChild, self).__init__()
        # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类B的对象 FooChild 转换为类 FooParent 的对象
        print('Child')
    def bar(self, message):
        super(FooChild, self).bar(message)  #重写父类的方法
        print('Child bar fuction')
        print(self.parent)
if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar('HelloWorld')

输出:

Parent
Child
HelloWorld from Parent
Child bar fuction
I'm the parent.

3、复杂场景的类继承(钻石继承)

# 砖石继承采用super(),防止了基类被初始化两次
# 其先采用广度搜索,找到基类,顺序为:Leaf()——>Medium1——>Medium2——>Base
# 其初始化的顺序为:Base——>Medium2——>Medium1——>Leaf
class Base(object):
    def __init__(self):
        print("Base")

class Medium1(Base):
    def __init__(self):
        super(Medium1, self).__init__()
        print("Medium1")

class Medium2(Base):
    def __init__(self):
        super(Medium2, self).__init__()
        print("Medium2")

class Leaf(Medium1, Medium2):
    def __init__(self):
        super(Leaf, self).__init__()
        print("Leafinit")
Leaf()

输出:

Base
Medium2
Medium1
Leafinit

 4、类的方法

# 1、实例方法:只能通过实例调用,实例方法第一个定义的参数只能是实例本身引用

class Myclass:
  def foo(self):
    print(id(self),'foo')


a = Myclass()  # 既然是实例对象,那就要创建实例
a.foo()  # 输出类里的函数地址
print(id(a))  # 输出类对象的地址
# 结果地址一样


print("******************************")


# 2、类方法:定义类方法,要使用装饰器@classmethod,定义的第一个参数是能是类对象的引用,
# 可以通过类或者实例直用
class Myclass:
    @classmethod # 类装饰器
    def foo2(cls):
        print(id(cls),'foo2')
      #类对象,直接可以调用,不需要实例化
print(id(Myclass),'classmethod')
Myclass.foo2()#直接使用类名可以调用


print("******************************")

# 3、静态方法:定义静态方法使用装饰器@staticmethod,没有默认的必须参数,
# 通过类和实例直接调用
class Myclass:
    @staticmethod  # 静态方法
    def foo3():
        print('foo3')
Myclass.foo3()  # 没有参数
# 结果foo3


输出:
2197397372264 foo
2197397372264
******************************
2197777487112 classmethod
2197777487112 foo2
******************************
foo3

 

posted @ 2019-05-19 13:16  泽积  阅读(225)  评论(0编辑  收藏  举报