Python中__dict__属性的详解(思维导图版)

1 篇文章 0 订阅
1 篇文章 0 订阅

__dict__属性的使用

在这里插入图片描述

# -*- coding: utf-8 -*-
class A(object):
    a = 0
    name = None
    b = 1
    def __init__(self,name):
        self.a = 2
        self.b = 3
        self.name = name
    def test(self):
        print ('a normal func.')
class B(A):
    def test_B(self):
        print ('func named test_B')
obj = A('Tom')
obj1 = B('Jerry')
print (A.__dict__)
print (obj.__dict__)
print (obj.__dict__['name'])
print (B.__dict__)
print (obj1.__dict__)
#执行结果如下
{'__module__': '__main__', 'a': 0, 'name': None, 'b': 1, '__init__': <function A.__init__ at 0x00000200C2D61840>, 'test': <function A.test at 0x00000200C2D618C8>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}

{'a': 2, 'b': 3, 'name': 'Tom'}

Tom #可以通过键来获取对象__dict__属性中的值
{'__module__': '__main__', 'test_B': <function B.test_B at 0x00000200C2D61950>, '__doc__': None}

{'a': 2, 'b': 3, 'name': 'Jerry'}


__dict__属性总结

1.类__dict__属性中包括类属性,类方法(非系统默认的,修改过的__init__()等,自己写的静态非静态方法),包括它实例化对象的方法
2.对象的属性就是__init__方法中带有的属性,子类默认继承父类__init__时候,子类创建对象的属性与父类一致,取决于你是否重写__init__属性,你可以尝试在子类重写__init__方法,并修改属性
3.可以通过操作对象__dict__属性来获取对象的属性。有时候会用到

参考博客:https://www.cnblogs.com/alvin2010/p/9102344.html

  • 3
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值