Python 学习笔记(四)

date: 2019-09-11

我使用的Python版本为3.7,没有装配环境的同学可以到下方链接查看教程。

面向对象之继承

基础语法

class Person(object):
    def __init__(self, name):
        self.name = name
class Student(Person):
    def __init__(self, name, score):
        super(Student, self).__init__(name)
        self.score = score
p = Student("Tom", 100)
print(p.name, p.score)
# Tom 100

这是一段继承的基础语法,super函数返回的是一个可以调用父类方法的对象,可以避免父类的方法被子类的同名方法屏蔽,传入两个参数:类名和对象本身。

在多重继承的背景下,我们推荐使用super来调用父类的初始化方法,首先它只需要一行(当然需要设计好参数传递的方法),其次它能保证父类的初始化方法只被调用一次。

多重继承

当我们遇到多重继承时,就会发现super最大的好处:

class A(object):
    def __init__(self):
        print('init A...')
class B(A):
    def __init__(self):
        super(B, self).__init__()
        print('init B...')
class C(A):
    def __init__(self):
        super(C, self).__init__()
        print('init C...')
class D(B, C):
    def __init__(self):
        super(D, self).__init__()
        print('init D...')
d = D()
# init A...
# init C...
# init B...
# init D...

虽然BC的初始化方法都被调用了,但A的初始化方法只调用了一次,可以有效避免初始化方法的重复调用

这里要额外提一句,super在对父类的初始化方法进行查找时,采用的是广度优先

对类使用的几个函数

  • isinstance:判断对象是否属于某个类型
  • type:返回对象类型
  • dir:返回对象的所有属性名(包括方法等)
  • setattr:设置对象的属性值
  • getattr:获得对象的属性值(如果属性不存在会报错,可以传入第三个参数,当不存在时返回它)

其中isinstance要牢记一句话:子类是父类,父类不是子类。

拍一段代码吧:

class Person(object):
    def __init__(self, name):
        self.name = name
class Student(Person):
    def __init__(self, name, score):
        super(Student, self).__init__(name)
        self.score = score
p = Student("Tom", 100)
t = Person("Jack")
print(isinstance(p, Person))
# True
print(isinstance(p, Student))
# True
print(isinstance(t, Person))
# True
print(isinstance(t, Student))
# False
print(type(p))
# <class '__main__.Student'>
print(dir(p))
# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'score']
setattr(p, "score", 200)
print(getattr(p, "score"))
# 200
print(getattr(p, "age", 20))
# 20

个人博客:https://wilfredshen.cn/

posted @ 2020-05-08 23:54  三尺青锋丶  阅读(105)  评论(0)    收藏  举报