其他分享
首页 > 其他分享> > day23-1 isinstance、issubclass和反射

day23-1 isinstance、issubclass和反射

作者:互联网

目录

isinstance和issubclass

class Foo:
    pass

f = Foo()
print(isinstance(f,Foo))  # f是Foo的实例化对象,所以打印True
True
class Foo(object):
    pass

class Bar(Foo):
    pass

print(isinstance(Bar(), Foo))  # 可以检查父类
True
class Foo(object):
    pass

class Bar(Foo):
    pass

print(type(Foo()) == Foo)  # Foo()是Foo的实例化对象,type(Foo())就是Foo
print(type(Bar()) == Foo)  # Bar()是Bar的实例化对象,type(Bar())是Bar,所以返回False
True
False
class Foo:
    pass

class Bar(Foo):
    pass

print(issubclass(Bar,Foo))  # Bar是Foo的子类,所以打印True
True

反射(hasattr,getattr,setattr,delattr)

1.反射就是通过字符串来操作类或者对象的属性

2.反射本质就是在使用内置函数,其中反射有以下四个内置函数:

class Foo:
    school = 'oldboy'
    
    def __init__(self,name,age):
        self.name = name
        self.age = age

f = Foo('nick', '18')
print(hasattr(f, 'name'))  # True
print(hasattr(f, 'gender'))  # False

print(getattr(f, 'name'))  # nick
print(getattr(f, 'gender', None))  # 不存在该属性时返回第三个参数None,不写会报错

setattr(f, 'gender', 'male')
print(f.gender)  # male

delattr(f, 'gender')
print(f.__dict__)  # {'name': 'nick', 'age': '18'}

标签:isinstance,Bar,day23,issubclass,pass,print,Foo,True,class
来源: https://www.cnblogs.com/863652104kai/p/11066931.html