Python基础:函数、类、模块
- 函数
函数声明:
def function_name([arguments]):
"optional documentation string"
function_suite
返回值:如果没有显示的返回值,返回值为None
参数传递:形参都是引用传递,意味着在函数内部对形参的改变都会改变实参的值;当然也有例外,如果实参是不可以改变的对象,如字符串、元组,则是值传递(记住Python中所有的类型皆为对象)
一些有用的函数:
Function | Description |
dir([obj]) | Display attributes of object or the names of global variables if no parameter given |
help([obj]) | Display object's documentation string in a pretty-printed format or enters interactive help if no parameter given |
int(obj) | Convert object to an integer |
len(obj) | Return length of object |
open(fn, mode) | Open file fn with mode ('r' = read, 'w' = write) |
range([[start, ]stop[,step]) | Return a list of integers that begin at start up to but not including stop in increments of step; start defaults to 0, and step defaults to 1 |
raw_input(str) | Wait for text input from the user, optional prompt string can be provided |
str(obj) | Convert object to a string |
type(obj) | Return type of object (a type object itself!) |
- 类
类的声明:
class ClassName (base_class[es]):
"optional documentation string"
static_member_declarations
method_declarations
__init__函数:类似与C++中的constructor,但是又不完全像C++中的constructor函数。__init__函数只是对象在实例话之后第一个调用的函数,与C++中constructor函数对应的函数应该是__new__函数。
创建类的实例:
foo1 = FooClass()
- 模块
导入模块:
import module_name
调用模块内的函数或者访问变量:
module.function()
module.variable