三小时快速入门Python第四篇--函数与对象
函数与对象
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· 因为Apifox不支持离线,我果断选择了Apipost!