自省机制与Super()函数

12月 18, 2020 966点热度 1人点赞 5条评论

Python 自省机制

自省是通过一定的机制查询到对象的内部结构

自省(introspection)机制有:dir(), type(), hasattr(), isinstance(), 通过这些函数,我们能够在运行程序时得知对象的类型,判断对象是否存在某个属性,访问对象的属性。

class Person(object):
    name = "小永"

class Student(Person):  # 继承Person()类
    def __init__(self, class_name):
        self.class_name = class_name

abc = Student("搞笑班")
# 访问当前对象
print(abc.__dict__)  # __dict__ 查看属性 key值为属性,value为属性的值
>>> {'class_name': '搞笑班'}

print(dir(abc))  # 返回[]列表数据类型,考虑到继承的成员
Super函数

在多继承下,super函数查询父类的顺序,或者直接调用类?

以下为广度优先的原则

class A(object):
    def __init__(self):
        print("A")

class C(A):
    def __init__(self):
        print("B")
        # 重写父类的构造方法 再调用父类的方法
        super().__init__()

class B(A):
    def __init__(self):
        print("C")
        super().__init__()

class D(B,C):
    def __init__(self):
        print("D")
        super().__init__()

if __name__ == '__main__':
    d = D()
class Person(object):
    def __init__(self, name, age, weight)
        self.name = name
        self.age = age
        self.weight = weight

class Student(Person): # 继承Person类
    def __init__(self, name, age, weight)
        # 软编码 --> 父类的名字可以随便改
        super().__init__(name, age, weight)

        # 硬编码
        # Person.__init__(self, name, age, weight)
        self.grade = grade

    def speak(self):
        print(f"{self.name}说:我{self.age}岁,我在{self.grade}年纪")

yy = Student('yy', 18, 65, 6)
yy.speak()

YY部落站(Admin)

当你能梦的时候就不要放弃梦~😎

文章评论

  • pożyowa

    I got what you intend, bookmarked, very decent website.

    1月 2, 2021
  • car**k

    I am incessantly thought about this, thanks for posting.

    1月 3, 2021
  • ch**dh

    I reckon something truly special in this website.

    1月 3, 2021
  • ren**

    Some really great info, Gladiola I detected this. I'm not spaming. I'm just saying your website is AWSOME! Thank you so much! Please vist also my website.

    1月 3, 2021
  • car**y

    Really nice design and good subject material.

    1月 3, 2021