Python中方法method的定义
引入
Python中的“方法”(method)即为编程中 “函数”(Function)。两者概念相同,在Python书上可能会看到“方法”一词。
1 基础
1.1 无输入参数无返回值的方法
def laugh(): # def是definition的缩写,后面跟的是方法名
print "ha"
laugh()方法的使用:
laugh() # 方法名后有一对括号
运行结果
ha
1.2 带单个输入参数无返回值的方法
def laugh(n): # n是输入参数
print "ha"*n
laugh(4)
# 运行结果
hahahaha
1.3 带多个输入参数无返回值的方法
def laugh(name, n):
print name, "is laughing:", "ha"*n
laugh("Alice", 3)
laugh("Bob", 1)
# 运行结果
Alice is laughing: hahaha
Bob is laughing: ha
1.4 输入参数有默认值方法
def laugh(name="One person", n):
print name, "is laughing:", "ha"*n
如未指定输入参数name, name即为默认值"One person"
laugh(3)
laugh(name="Alice", n=1)
运行结果
One person is laughing: hahaha
Alice is laughing: ha