python class继承

https://blog.csdn.net/brucewong0516/article/details/79121179

类继承:

class SubClassName(parentClass,[,parentClass2,..]):
        class_suite

实现继承之后,子类将继承父类的属性,也可以使用内建函数insubclass()来判断一个类是不是另一个类的子孙类

issubclass(Child, Parent),其中,child和parent都是class,child继承parent

class Parent(object):
    '''
    parent class
    '''
    numList = []
    def numdiff(self, a, b):
        return a-b

class Child(Parent):
    pass


c = Child()    
# subclass will inherit attributes from parent class 
#子类继承父类的属性   
Child.numList.extend(range(10))
print(Child.numList)

print("77 - 2 =", c.numdiff(77, 2))

# built-in function issubclass() 
print(issubclass(Child, Parent))
print(issubclass(Child, object))

# __bases__ can show all the parent classes
#bases属性查看父类
print('the bases are:',Child.__bases__)

# doc string will not be inherited
#doc属性不会被继承
print(Parent.__doc__)
print(Child.__doc__)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
77 - 2 = 75
True
True
the bases are: (<class '__main__.Parent'>,)

    parent class

None

super的使用详解

  • super主要来调用父类方法来显示调用父类,在子类中,一般会定义与父类相同的属性(数据属性,方法),从而来实现子类特有的行为。也就是说,子类会继承父类的所有的属性和方法,子类也可以覆盖父类同名的属性和方法
class Parent(object):
    Value = "Hi, Parent value"
    def fun(self):
        print("This is from Parent")
#定义子类,继承父类               
class Child(Parent):
    Value = "Hi, Child  value"
    def ffun(self):
        print("This is from Child")
c = Child()    
c.fun()
c.ffun()
print(Child.Value)
This is from Parent
This is from Child
Hi, Child value

但是,有时候可能需要在子类中访问父类的一些属性,可以通过父类名直接访问父类的属性,当调用父类的方法是,需要将”self”显示的传递进去的方式

class Parent(object):
    Value = "Hi, Parent value"
    def fun(self):
        print("This is from Parent")

class Child(Parent):
    Value = "Hi, Child  value"
    def fun(self):
        print("This is from Child")
        Parent.fun(self)   #调用父类Parent的fun函数方法

c = Child()    
c.fun()
This is from Child
This is from Parent  #实例化子类Child的fun函数时,首先会打印上条的语句,再次调用父类的fun函数方法

这种方式有一个不好的地方就是,需要经父类名硬编码到子类中,为了解决这个问题,可以使用Python中的super关键字:

class Parent(object):
    Value = "Hi, Parent value"
    def fun(self):
        print("This is from Parent")

class Child(Parent):
    Value = "Hi, Child  value"
    def fun(self):
        print("This is from Child")
        #Parent.fun(self)
        super(Child,self).fun()  #相当于用super的方法与上一调用父类的语句置换

c = Child()    
c.fun()
This is from Child
This is from Parent  #实例化子类Child的fun函数时,首先会打印上条的语句,再次调用父类的fun函数方法
对于所有的类,都有一组特殊的属性
_ _ name_ _:类的名字(字符串)
_ _ doc _ _ :类的文档字符串
_ _ bases _ _:类的所有父类组成的元组
_ _ dict _ _:类的属性组成的字典
_ _ module _ _:类所属的模块
_ _ class _ _:类对象的类型

copy from https://blog.csdn.net/brucewong0516/article/details/79121179

猜你喜欢

转载自www.cnblogs.com/lucky466/p/10260459.html