python 特殊的类属性

首先我们定义一个类,如下:

class Test(object):
    '''
    hello test
    '''
    COUNT = 0
    
    def run(self):
        pass


我们利用内置函数 dir来看下这个Test类中有什么属性和方法:


>>> dir(test.Test)
['COUNT', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduc
e_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'run']

可以看到,除了我们本身定义的数据COUNT和一个run方法外,还有许多带有“__”的属性,这些以__开头的属性,就是一个python类中的特殊的内置属性了。


下面我们介绍主要的几个:

1. __class__:表示类的类型

>>> print test.Test.__class__
<type 'type'>

2. __doc__:类的文档字符串

>>> print test.Test.__doc__

    hello test

可以看到,我们在定义类名的下一行写上的字符串注释,即为__doc__的内容,所以在今后定义类的时候,最好有此注释


3.__dict__:类的属性

>>> print test.Test.__dict__
{'COUNT': 0, '__module__': 'test', 'run': <function run at 0x0260CB70>, '__dict__': <attribute '__dict__' of 'Test' objects>, '__weakref__': <attribute '__weakref__'
of 'Test' objects>, '__doc__': '\n    hello test\n    '}

可以看到,__dcit__是一个以key-value形式展示的字典,展示出属性所对应的值


4.__module__:表示类所在的模块

>>> test.Test.__module__
'test'
我的文件名叫test.py,所以展示的test,表示所在的模块名


其他的后续补充~~~




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值