python 特殊的类属性

来源:互联网 发布:c语言碎纸片拼接技术 编辑:程序博客网 时间:2024/06/05 06:08

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

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__', '__reduce_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,表示所在的模块名


其他的后续补充~~~




原创粉丝点击