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__': , '__doc__': None}
#父类返回的结果:
{'__module__': '__main__', 'name': 'Mike', 'age': 18, '__dict__': , '__weakref__': , '__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

  • 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类

你可能感兴趣的:(2021-03-16 Python自省机制)