Python3基础-内置函数补充以及getattribute

isinstance(object,class) 检查是否object是类class的对象

issubclass(sub,super) 检查 sub类是否是super的派生类

class People:
    def __init__(self,name):
        self.name = name
    def eat(self, food):
        print("%s正在吃%s"%(self.name,food))

class Student(People):
    pass

p1 = People('苏苏')
stu1 = Student('小花')
print(isinstance(p1,People))  #返回True
print(isinstance(stu1,Student)) #返回True
print(isinstance(stu1,People)) #返回True
print(issubclass(Student,People)) #返回True

__getattribute__()

class People:
    nationality='china'
    def __init__(self,name):
        self.name=name

    #__getattr__:当使用点号获取实例属性时,如果属性不存在就自动调用__getattr__方法
    def __getattr__(self, item):
        print('__getattr__:调用一个不存在的对象属性时候,执行',item)

    def __getattribute__(self, item): #无条件的调用
        print('执行的是__getattribute__',item)
        if item == 'name':
            print('哈哈哈哈')
        else:
            raise AttributeError('抛出异常了') #抛出异常的时候,就会自动调用 __getattr__

p1 = People('苏苏')
print(p1.name)
print(p1.age)
"""
执行结果如下:
执行的是__getattribute__ name
哈哈哈哈
None
执行的是__getattribute__ age
__getattr__:调用一个不存在的对象属性时候,执行 age
None
"""

注意:getattribute无条件被调用,通过实例访问属性。如果class中定义了__getattribute__(),则__getattr__()不会被调用(除非显示调用或引发AttributeError异常)

 

posted @ 2019-11-18 18:24  槑槑DE  阅读(148)  评论(0编辑  收藏  举报