python __str__(),__dir__(),__doc__


对于一个类的属性查看,用dir

__str__() 是介绍这个类的信息

__doc__ 这个是文档字符串,也是介绍


对于dir的用法

>>> import os
>>> try:
...     a = 1/0
... except Exception,reason1:
...     print "can't /"
...
can't /
>>> print reason1
integer division or modulo by zero
>>> print reason1.__str__()
integer division or modulo by zero
>>> dir(reason1)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', 'args', 'message']
>>> print reason1.__doc__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>> print reason1.__doc__
Second argument to a division or modulo operation was zero.
>>> print reason1.__str__
<method-wrapper '__str__' of exceptions.ZeroDivisionError object at 0x10c095b90>
>>> print reason1.__calss__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'exceptions.ZeroDivisionError' object has no attribute '__calss__'
>>> print reason1.__class__
<type 'exceptions.ZeroDivisionError'>
>>> type(reason1.__doc__)
<type 'str'>
>>>

对于dir,它显示的是类的所有的属性和方法。

中文说明:不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。

如果参数包含方法__dir__(),该方法被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值