# 魔法方法dir, __dir__, __dict__class Student:address = "wh" # 类属性def __init__(self, name):self.name = name # 对象属性self._age = 20self.__tel = "123456"@staticmethoddef static_func():...# __dir__: 查看对象的方法和属性
st = Student("zs")print(st.__dir__())
# ['name', '__module__', 'address', '__init__', '__dict__', '__weakref__', '__doc__', '__new__', '__repr__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__reduce_ex__', '__reduce__', '__getstate__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__'] # 将对__dir__返回值排序并包装为列表
print(dir(st))
# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'address', 'name']# __dict__:是一个字典
# 用于类,存储所有实例共享的属性和方法
# 用于对象,存储对象所有属性和值,一般用于动态读取和设置属性print(Student.__dict__)
# 存在address和static_func
# {'__module__': '__main__', 'address': 'wh', '__init__': <function Student.__init__ at 0x0000021E49E21800>, 'static_func': <staticmethod(<function Student.static_func at 0x0000021E49E218A0>)>, '__dict__': <attribute '__dict__' of 'Student' objects>, '__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None}print(st.__dict__)
# {'name': 'zs', '_age': 20, '_Student__tel': '123456'}# 获取已存在属性
print(st.__dict__['name']) # zs
# 设置新属性
st.__dict__["grade"] = 60
print(st.__dict__.get("grade")) # 60