2021-03-16 Python自省机制

逻辑教育.png

Python语言的自省(introspection)机制

在计算机编程中,自省是指语言能自动识别数据类型或对象属性的一种能力,在程序编写代码时,不必为变量声明数据类型,在程序运行时,编程语言能够自动识别变量的数据类型,以及对象的属性与方法。简单一句就是,运行时能够获知对象的类型。

python, buby, object-C, c++都有自省的能力,这里面的c++的自省的能力最弱,只能够知道是什么类型,而像python可以知道是什么类型,还有什么属性。

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


1.dir()

先查看一下dir()的注释文档

"""
dir([object]) -> list of strings
    
    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise the default dir() logic is used and returns:
        for a module object: the module's attributes.
        for a class object:  its attributes, and recursively the attributes of its bases.
        for any other object: its attributes, its class's attributes, and recursively the attributes of its class's base classes.
"""

翻译一下:
dir([object])->字符串列表

如果在没有参数的情况下调用,则返回当前作用域中的名称。

否则,返回一个列表,列表中的元素是对象的属性,其顺序是按字母顺序排列的。

如果对象重写了_dir_()的方法,则执行重写内容;否则使用默认的dir()逻辑并返回:

对于模块对象,返回模块的属性。

对于类对象,返回类的属性,及其父类的属性。

对于任何其他对象,返回对象属性、类的属性和基类的属性。

class A(object):
    def __init__(self):
        self.name = "Mike"
        self.age = 18

class B(A):
    def __init__(self, weight):
        super().__init__()
        self.weight = weight 

b = B(60)
print("参数为空:", dir())
print("参数为对象:", dir(b))
print("参数为子类:", dir(B))
print("参数为父类:", dir(A))
  • 运行结果:
参数为空: ['A', 'B', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'b']
参数为对象: ['__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__', 'age', 'name', 'weight']
参数为子类: ['__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__']
参数为父类: ['__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__']

2._dict_()

当对象引用_dict_()方法返回对象在当前类中的属性,不考虑继承关系。
如果是类引用该方法,则返回这个类中包含的属性和方法,同样不会返回继承的类中的属性和方法。
返回的结果是字典。

class A(object):
    name = "Mike"
    age = 18

class B(A):
    def __init__(self, weight):
        self.weight = weight

b = B(60)
print(b.__dict__)
print(B.__dict__)
print(A.__dict__)
  • 运行结果:
#对象返回的结果:
{'weight': 60}
#子类返回的结果:
{'__module__': '__main__', '__init__': <function B.__init__ at 0x0000000002986D90>, '__doc__': None}
#父类返回的结果:
{'__module__': '__main__', 'name': 'Mike', 'age': 18, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}

3.hasattr()

  • 注释文档:
"""
    Return whether the object has an attribute with the given name.
    
    This is done by calling getattr(obj, name) and catching AttributeError.
"""
  • hasattr()函数返回一个布尔值,如果对象含有一个属性返回True,否则返回False。
  • hasattr(*args, **kwargs)含有两个参数,第一个是对象名,第二个属性名,第二个参数传入时必须是字符串。
class Demo(object):
    name = "Mike"

    def __init__(self, age):
        self.age = age

d = Demo(18)
print(hasattr(d, "name"))
print(hasattr(d, "age"))
print(hasattr(d, "__doc__"))
  • 运行结果:
True
True
True

4.isinstance()与type()

(1) isinstance()

  • 查看isinstance()源码:
def isinstance(x, A_tuple): # real signature unknown; restored from __doc__
    """
    Return whether an object is an instance of a class or of a subclass thereof.
    
    A tuple, as in "isinstance(x, (A, B, ...))", may be given as the target to
    check against. This is equivalent to "isinstance(x, A) or isinstance(x, B)
    or ..." etc.
    """
    pass
  • 在源码中,可以看到isinstance()返回的是一个布尔值,返回对象是否为类的实例或者是子类的实例。
  • isinstance(x, A_tuple)的第二个参数是元组,如isinstance(x,(A,B)中的元组,可以作为检查的目标,如果x是A或者B中的实例对象返回Ture。这相当于isinstance(x,A)或isinstance(x,B)或...

(2)type()

  • 查看type()源码:
class type(object):
    """
    type(object_or_name, bases, dict)
    type(object) -> the object's type
    type(name, bases, dict) -> a new type
    """
    pass
  • 首先要注意到type()是一个类,这个类有两个作用,第一个作用是判断一个对象的类型,另一个作用是定义一个新的对象类型。这里只讨论第一个作用。

(3) 对比isinstance()与type()的两个差别:

  • 差别1:基本使用方法
a = 1
b = "hello world"

print(isinstance(b, (int, str)))
print(type(a))
  • 差别1运行结果:
True
<class 'int'>
  • isinstance()返回布尔值,第二个参数是元组,元组中的元素可以有多个,其逻辑关系是or,即只要对象满足其中一个类型就是True,都不满足时才是False。

  • type()直接返回对象的类型。

  • 差别2:继承关系不同

class A(object):
    pass

class B(A):
    pass

a = A()
b = B()
print(isinstance(a,(A,)))
print(isinstance(b,(A,)))
print(type(a) is A)
print(type(b) is A)
  • 差别2运行结果:
True #说明a是A类的实例对象
True #说明b是A类的实例对象,如果有继承关系,认为对象也是父类对象的实例。
True #说明a是A类的实例对象
False #说明a不是A类的实例对象,也就是type()不会考虑类的继承,只对当前类的实例对象作出判断。

5.issubclass()

  • 查看源码:
def issubclass(x, A_tuple): # real signature unknown; restored from __doc__
    """
    Return whether 'cls' is a derived from another class or is the same class.
    
    A tuple, as in "issubclass(x, (A, B, ...))", may be given as the target to check against. This is equivalent to "issubclass(x, A) or issubclass(x, B) or ..." etc.
    """
    pass
  • 返回“cls”是从另一个类派生的还是同一个类。
  • 第二个参数是元组,如issubclass(x,(A,B,…)中的元组,可以作为检查的目标。这相当于issubclass(x,A)或issubclass(x,B)或…等。
class CacheBase(object):
    pass

class RedisBase(CacheBase):
    pass


print(issubclass(RedisBase, CacheBase))

print(issubclass(int,type))
  • 运行结果:
True
False
  • 当子类继承自父类时,issubclass()返回True;int继承自object类,所以返回值为False,说明int类不是继承自type类
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,406评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,732评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,711评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,380评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,432评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,301评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,145评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,008评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,443评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,649评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,795评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,501评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,119评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,731评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,865评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,899评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,724评论 2 354

推荐阅读更多精彩内容