# 魔法方法dir, __dir__, __dict__
class Student:
address = "wh" # 类属性
def __init__(self, name):
self.name = name # 对象属性
self._age = 20
self.__tel = "123456"
@staticmethod
def 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__': , 'static_func': )>, '__dict__': , '__weakref__': , '__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