__dict__只能查询自身的属性,但是也能创建属性,如下:
class Person:
address = '海洋小区'
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, school_name):
self.school_name = school_name
stu = Student('黑马')
print(stu.__dict__)
print(Student.__dict__)
print(Person.__dict__)
stu.__dict__['age'] = 18
print(stu.__dict__)
print(dir(stu))
结果
{'school_name': '黑马'}
{'__module__': '__main__', '__init__': <function Student.__init__ at 0x000002050370C9D8>, '__doc__': None}
{'__module__': '__main__', 'address': '海洋小区', '__init__': <function Person.__init__ at 0x00000204F0DF9840>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
{'school_name': '黑马', 'age': 18}
['__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__', 'address', 'age', 'school_name']