函数与对象
1、函数
1 # 使用 "def" 来创建一个新的函数
2 def add(x, y):
3 print ("x is {0} and y is {1}".format(x, y))
4 return x + y # 用 return 语句返回值
5 # 调用函数
6 add(5,6) #=>prints out "x is 5 and y is 6" 返回值为11
7 # 使用关键字参数调用函数
8 add(y=6, x=5) # 关键字参数可以不在乎参数的顺序
9 # 函数的参数个数可以不定,使用*号会将参数当作元组
10 def varargs(*args):
11 return args
12 varargs(1, 2, 3) # => (1, 2, 3)
13
14 # 也可以使用**号将参数当作字典类型
15 def keyword_args(**kwargs):
16 return kwargs
17 # 调用一下试试看
18 keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
19
20 # 两种类型的参数可以同时使用
21 def all_the_args(*args, **kwargs):
22 print (args)
23 print (kwargs)
24 """
25 all_the_args(1, 2, a=3, b=4) prints:
26 (1, 2)
27 {"a": 3, "b": 4}
28 """
29
30 # When calling functions, you can do the opposite of args/kwargs!
31 # Use * to expand positional args and use ** to expand keyword args.
32 args = (1, 2, 3, 4)
33 kwargs = {"a": 3, "b": 4}
34 all_the_args(*args) # 相当于 foo(1, 2, 3, 4)
35 all_the_args(**kwargs) # 相当于 foo(a=3, b=4)
36 all_the_args(*args, **kwargs) # 相当于 foo(1, 2, 3, 4, a=3, b=4)
37 # you can pass args and kwargs along to other functions that take args/kwargs
38 # by expanding them with * and ** respectively
39 def pass_all_the_args(*args, **kwargs):
40 all_the_args(*args, **kwargs)
41 print (varargs(*args))
42 print (keyword_args(**kwargs))
43
44 # Returning multiple values (with tuple assignments)
45 # 多个返回值
46 def swap(x, y):
47 return y, x # Return multiple values as a tuple without the parenthesis.
48 # (Note: parenthesis have been excluded but can be included)
49
50 x = 1
51 y = 2
52 x, y = swap(x, y) # => x = 2, y = 1
53 # (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included.
2、函数作用域
1 x=5
2 def set_x(num):
3 # 局部变量x与全局变量x不相同
4 x = num # => 43
5 print(x) # => 43
6 def set_global_x(num):
7 global x
8 print(x) # => 5
9 x = num # 全局变量被设置成为6
10 print(x) # => 6
11 set_x(43)
12 set_global_x(6)
13
14 # 函数也可以是对象
15 def create_adder(x):
16 def adder(y):
17 return x + y
18 return adder
19 add_10 = create_adder(10)
20 add_10(3) # => 13
21 # 匿名函数
22 (lambda x: x > 2)(3) # => True
23 (lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
24 # 高阶函数
25 map(add_10, [1, 2, 3]) # => [11, 12, 13]
26 map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
27 filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
28 # We can use list comprehensions for nice maps and filters
29 [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
30 [x for x in[3,4,5,6,7] if x>5] #=>[6,7]
3、面向对象
# 继承 object 创建一个子类
class Human(object):
# 一个类属性,所有该类的实例都可以访问
species = "H. sapiens"
# 基础实例化方法,在创建一个实例时调用
# 注意在名称前后加双下划线表示对象或者属性是 Python 的特殊用法,但用户可以自己控制
# 最好不要在自己的方法前这样使用
def __init__(self, name):
# 将参数赋值给实例属性
self.name = name
# 初始化属性
self.age = 0
# 一个实例方法。所有实例方法的第一个属性都是self
def say(self, msg):
return "{0}: {1}".format(self.name, msg)
# A class method is shared among all instances
# They are called with the calling class as the first argument
@classmethod
def get_species(cls):
return cls.species
# A static method is called without a class or instance reference
@staticmethod
def grunt():
return "*grunt*"
# A property is just like a getter.
# It turns the method age() into an read-only attribute
# of the same name.
@property
def age(self):
return self._age
# This allows the property to be set
@age.setter
def age(self, age):
self._age = age
# This allows the property to be deleted
@age.deleter
def age(self):
del self._age
# 创建一个实例
i = Human(name="Ian")
print(i.say("hi")) # prints out "Ian: hi"
j = Human("Joel")
print(j.say("hello")) # prints out "Joel: hello"
# 调用类方法
i.get_species() # => "H. sapiens"
# 访问共有变量
Human.species = "H. neanderthalensis"
i.get_species() # => "H. neanderthalensis"
j.get_species() # => "H. neanderthalensis"
# 调用静态方法
Human.grunt() # => "*grunt*"
# Update the property
i.age = 42
# Get the property
i.age # => 42
# Delete the property
del i.age
i.age # => raises an AttributeError
上一篇:三小时快速入门Python第三篇--控制流分支与循环
下一篇:三小时快速入门Python第五篇--异常处理与迭代器