Python中的自省机制(__dict__和dir)

自省机制

一、定义

自省就是通过一定的机制查询到对象的内部结构

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__指弱引用,__doc__指文档,即类中的""" ..."""

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

二、dir函数

dir函数可以列出对象里面的所有属性,但只有属性名称,没有属性的值。

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__']等等

猜你喜欢

转载自blog.csdn.net/weixin_43901214/article/details/106917793
今日推荐