Introspection mechanism in Python (__dict__ and dir)

Introspection mechanism

1. Definition

Introspection is to query the internal structure of the object through a certain mechanism

class Person:
    """
   
    """
    name="User"

class Student(Person):
    def __init__(self,school_name):
        self.school_name = school_name
if __name__ = "__main__":
    user = Student("小明")
    
#通过__dict__查询属性 
print(user.__dict__) # {’school_name‘:’小明‘}
print(user.name) # user

print(Person.__dict__) 
# {'__module__':'__main__','__name__':'__user__','__dict__':<attribute'__dict__' of 'Person' objects>,'__weakref__':<attribute'__weakref__' of 'Person' objects>,'__doc__':None}

__weakref__Refers to weak references, __doc__refers to documents, that is, in the class""" ..."""

# 赋值
user.__dict__["school_addr"] = "北京市"
print(user.school_addr) # 北京市

Two, dir function

dirThe function can list all the attributes in the object, but only the attribute name and no attribute value.

print(dir(user))
#['__class__','__delattr__','__dict__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__gt__','__hash__'] 还有很多
a=[1,2]
print(a.__dict__) 
#'list' object has no attribute '__dict__'

print(dir(a))
#['__add__','__class__','__contains__','__delitem__','__dir__']等等

Guess you like

Origin blog.csdn.net/weixin_43901214/article/details/106917793