Menu
CoddyTech

文档字符串

Coddy Clean Code:用 Python 写出更好的代码 课程的第 8 课,共 28 课。

文档字符串(Docstring)通常位于模块、函数、类或方法定义中的第一条语句。

用 """ 或 ''' 将字符串括起来,即可声明文档字符串,例如:

def complex(real=0.0, imag=0.0):
	"""
	构造一个复数。
	
		Parameters:
			real(float):实部(默认值为 0.0)
			imag(float):虚部(默认值为 0.0)
	"""
    if imag == 0.0 and real == 0.0:
        return complex_zero
    ...

看看它是如何为 complex(real, imag) 函数编写文档的。 

注意文档字符串正文和 """ 的缩进。

使用这样的文档字符串后,你可以通过 __doc__ 属性获取文档:

complex.__doc__

输出如下:

Form a complex number.
	
	Parameters:
		real (float) -- the real part (default 0.0)
		imag (float) -- the imaginary part (default 0.0)
challenge icon

挑战

简单

给你一个函数,其中使用了块注释而不是文档字符串。

你的任务是将它替换为有效的文档字符串,并查看测试用例,确保文档字符串的格式正确!

亲手试试

def sum_binary(a, b):
    # Calculate sum of two integers in binary formmated string
    # Parameters:
    # a (int) -- Integer number
    # b (int) -- Another integer number
    # Returns:
    # binary_sum (str) -- The sum of a and b in binary format
    sum = a + b
    binary_sum = bin(sum)
    return str(binary_sum)[1:] # Final formmating

print(sum_binary.__doc__)

Clean Code:用 Python 写出更好的代码中的所有课

自己练习: Python 在线编译器