1.使用 repr 显示内容及类型信息
python内置的 print 函数有时会隐藏值得类型信息
b = 5
a = '5'
print(b, a)
5 5 只通过 print 函数无法得知其数据类型
b = repr(5)
a = repr('5')
print(b, a)
5 '5' 通过 repr 函数直观的看出其数据类型
2.为程序编写测试代码
使用Python内置的 unittest (单元测试)
from unittest import TestCase, main
def to_str(value):
''定义一个转字符串函数''
if isinstance(value, str):
return value
elif isinstance(value, bytes):
return value.decode('utf8')
else:
raise TypeError('type error')
class Test(TestCase):
def test_bytes(self): 检测是否相等
self.assertEqual('hello', to_str(b'hello'))
def test_str(self):
self.assertEqual('hello', to_str('hello'))
def test_bad(self): 检测是否抛出错误
self.assertRaises(TypeError, to_str, object())
if __name__ == '__main__':
main()
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
3.函数的断点调试
def test():
a = 5
print(a)
import pdb; pdb.set_trace()
'hello Mr dj 这节奏不要停'
'aaaa'
在疑问代码处加上此内容,会触发互动调试器,使程序执行到此后终止
方便调试看出问题
test()
5
> c:\users\lenovo\pycharmprojects\online\online\app1\tests.py(410)test()
-> 'aaaa'
(Pdb)
4.特性覆盖类属性
class Test:
data = 'the class data'
a = Test()
print(a.data) 返回类属性 'the class data'
a.name = 'data'
print(a.name) 返回对象属性 'data'
若与类属性同名的对象属性存在, 则返回对象属性