python魔法__dir__和__dict__

# 魔法方法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__': <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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值