本文涉及内容为阿里云天池学习中心python训练营课程,部分内容摘自课程课件,剩余部分来自编者理解与网络搜索补充算是训练营课程的部分内容精简版,若有问题或错误欢迎留言,如有侵权和冒犯可联系删除。
一、函数
1.函数的定义
- 函数以
def
关键词开头,后接函数名和圆括号()。 - 函数执行的代码以冒号起始,并且缩进。
- return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回
None
def functionname (parameters):
"函数文档字符串"
functionsuite
return [expression]
2、函数的调用
调用函数也就是执行函数。如果把创建的函数理解为一个具有某种用途的工具,那么调用函数就相当于使用该工具。
定义一个函数只给了函数一个名称,指定了函数里包含的参数,和代码结构。
这个函数的基本结构完成以后,你可以通过另一个函数调用执行,也可以直接从Python提示符执行。
例子:
def printme(str):
print(str)
printme("我要调用用户自定义函数!") # 我要调用用户自定义函数!
printme("再次调用同一函数") # 再次调用同一函数
temp = printme('hello') # hello
print(temp) # None
3、函数的参数
Python 的函数具有非常灵活多样的参数形态,既可以实现简单的调用,又可以传入非常复杂的参数。从简到繁的参数形态如下:
- 位置参数 (positional argument)
- 默认参数 (default argument)
- 可变参数 (variable argument)
- 关键字参数 (keyword argument)
- 命名关键字参数 (name keyword argument)
- 参数组合
可变参数:
def sum(*lst): 参数前面加一个星号,表示这个参数是可变的,也就是说可以接受多个参数,将这些参数构成一个元组,只能通过为止参数传参
可变参数有两种形式:
- 位置可变参数 : 参数前加一个星号,参数构成一个元组,参数只能以 位置参数 的形式传参
- 关键字可变参数 : 参数前加两个星号,参数构成一个字典,参数只能以 关键字参数 的形式传参
当默认参数和可变参数一起出现的时候,默认参数相当于普通参数
通常来说:
- 默认参数靠后
- 可变参数靠后
- 默认参数和可变参数不同时出现
keyword-only: 必须以Key->Value对的形式出现的,叫做keyword-only
位置参数:
def functionname(arg1):
"函数文档字符串"
functionsuite
return [expression]
-
arg1
- 位置参数 ,这些参数在调用函数 (call function) 时位置要固定。
默认参数:
def functionname(arg1, arg2=v):
"函数文档字符串"
functionsuite
return [expression]
arg2 = v
- 默认参数 = 默认值,调用函数时,默认参数的值如果没有传入,则被认为是默认值。- 默认参数一定要放在位置参数 后面,不然程序会报错。
关键字参数:
关键字参数和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值
使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为python解释器能够用参数名匹配参数值
def printme(str):
"打印任何传入的字符串"
print(str)
printme(str="调用printme函数")
#运行结果
调用printme函数
命名关键字参数:
*, nkw
- 命名关键字参数,用户想要输入的关键字参数,定义方式是在nkw 前面加个分隔符*
。- 如果要限制关键字参数的名字,就可以用「命名关键字参数」
- 使用命名关键字参数时,要特别注意不能缺少参数名。
def functionname(arg1, arg2=v, args, *, nkw, *kw):
"函数文档字符串"
functionsuite
return [expression]
参数组合:
在 Python 中定义函数,可以用位置参数、默认参数、可变参数、命名关键字参数和关键字参数,这 5 种参数中的 4 个都可以一起使用,但是注意,参数定义的顺序必须是:
- 位置参数、默认参数、可变参数和关键字参数。
- 位置参数、默认参数、命名关键字参数和关键字参数。
要注意定义可变参数和关键字参数的语法:
*args
是可变参数,args
接收的是一个tuple
**kw
是关键字参数,kw
接收的是一个dict
命名关键字参数是为了限制调用者可以传入的参数名,同时可以提供默认值。定义命名关键字参数不要忘了写分隔符 *
,否则定义的是位置参数。
警告:虽然可以组合多达 5 种参数,但不要同时使用太多的组合,否则函数很难懂。
二、基本的魔法方法
1、魔法方法的基本介绍
魔法方法总是被双下划线包围,例如__init__
。
魔法方法是面向对象的 Python 的一切,如果你不知道魔法方法,说明你还没能意识到面向对象的 Python 的强大。
魔法方法的“魔力”体现在它们总能够在适当的时候被自动调用。
魔法方法的第一个参数应为cls
(类方法) 或者self
(实例方法)。
cls
:代表一个类的名称self
:代表一个实例对象的名称
2、常见的魔法方法
__init__(self[, ...])
构造器,当一个实例被创建的时候调用的初始化方法
class Rectangle:
def __init__(self, x, y):
self.x = x
self.y = y
def getPeri(self):
return (self.x + self.y) * 2
def getArea(self):
return self.x * self.y
rect = Rectangle(4, 5)
print(rect.getPeri()) # 18
print(rect.getArea()) # 20
实际上, 当我们调用x = SomeClass()
的时候调用,__init__
并不是第一个执行的, __new__
才是。所以准确来说,是__new__
和__init__
共同构成了"构造函数".
__new__
是用来创建类并返回这个类的实例, 而__init__
只是将传入的参数来初始化该实例.
__new__
在创建一个实例的过程中必定会被调用,但__init__
就不一定,比如通过pickle.load
的方式反序列化一个实例时就不会调用__init__
。
__new__
方法总是需要返回该类的一个实例,而__init__
不能返回除了None的任何值。比如下面例
子:
classFoo(object):
def__init__(self):
print 'foo __init__'
return None # 必须返回None,否则抛TypeError
def__del__(self):
print 'foo __del__'
剩下的一些复杂的方法需要读者更深层的探索
2、算术运算符
类型工厂函数,指的是“不通过类而是通过函数来创建对象”。
print(type(len)) # <class 'builtin_function_or_method'>
print(type(dir)) # <class 'builtin_function_or_method'>
print(type(int)) # <class 'type'>
print(type(list)) # <class 'type'>
print(type(tuple)) # <class 'type'>
print(type(C)) # <class 'type'>
print(int('123')) # 123
__add__(self, other)
定义加法的行为:+
__sub__(self, other)
定义减法的行为:-
例子:
class MyClass:
def __init__(self, height, weight):
self.height = height
self.weight = weight
# 两个对象的长相加,宽不变.返回一个新的类
def __add__(self, others):
return MyClass(self.height + others.height, self.weight + others.weight)
# 两个对象的宽相减,长不变.返回一个新的类
def __sub__(self, others):
return MyClass(self.height - others.height, self.weight - others.weight)
# 说一下自己的参数
def intro(self):
print("高为", self.height, " 重为", self.weight)
def main():
a = MyClass(height=10, weight=5)
a.intro()
b = MyClass(height=20, weight=10)
b.intro()
c = b - a
c.intro()
d = a + b
d.intro()
if __name__ == '__main__':
main()
# 高为 10 重为 5
# 高为 20 重为 10
# 高为 10 重为 5
# 高为 30 重为 15
__mul__(self, other)
定义乘法的行为:*
__truediv__(self, other)
定义真除法的行为:/
__floordiv__(self, other)
定义整数除法的行为://
__mod__(self, other)
定义取模算法的行为:%
__divmod__(self, other)
定义当被divmod()
调用时的行为divmod(a, b)
把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)
__pow__(self, other[, module])
定义当被power()
调用或**
运算时的行为__lshift__(self, other)
定义按位左移位的行为:<<
__rshift__(self, other)
定义按位右移位的行为:>>
__and__(self, other)
定义按位与操作的行为:&
__xor__(self, other)
定义按位异或操作的行为:^
__or__(self, other)
定义按位或操作的行为:|
就不再举例了
3、属性访问
__getattr__(self, name)
: 定义当用户试图获取一个不存在的属性时的行为。__getattribute__(self, name)
:定义当该类的属性被访问时的行为(先调用该方法,查看是否存在该属性,若不存在,接着去调用__getattr__
)。__setattr__(self, name, value)
:定义当一个属性被设置时的行为。__delattr__(self, name)
:定义当一个属性被删除时的行为。
class C:
def __getattribute__(self, item):
print('__getattribute__')
return super().__getattribute__(item)
def __getattr__(self, item):
print('__getattr__')
def __setattr__(self, key, value):
print('__setattr__')
super().__setattr__(key, value)
def __delattr__(self, item):
print('__delattr__')
super().__delattr__(item)
c = C()
c.x
# __getattribute__
# __getattr__
c.x = 1
# __setattr__
del c.x
# __delattr__
4、增值赋值运算符
此类运算符主要为以下几类:
__iadd__(self, other)
定义赋值加法的行为:+=
__isub__(self, other)
定义赋值减法的行为:-=
__imul__(self, other)
定义赋值乘法的行为:*=
__itruediv__(self, other)
定义赋值真除法的行为:/=
__ifloordiv__(self, other)
定义赋值整数除法的行为://=
__imod__(self, other)
定义赋值取模算法的行为:%=
__ipow__(self, other[, modulo])
定义赋值幂运算的行为:**=
__ilshift__(self, other)
定义赋值按位左移位的行为:<<=
__irshift__(self, other)
定义赋值按位右移位的行为:>>=
__iand__(self, other)
定义赋值按位与操作的行为:&=
__ixor__(self, other)
定义赋值按位异或操作的行为:^=
__ior__(self, other)
定义赋值按位或操作的行为:|=
5、描述符
描述符就是将某种特殊类型的类的实例指派给另一个类的属性。
__get__(self, instance, owner)
用于访问属性,它返回属性的值。__set__(self, instance, value)
将在属性分配操作中调用,不返回任何内容。__del__(self, instance)
控制删除操作,不返回任何内容。
例子:
class MyDecriptor:
def __get__(self, instance, owner):
print('__get__', self, instance, owner)
def __set__(self, instance, value):
print('__set__', self, instance, value)
def __delete__(self, instance):
print('__delete__', self, instance)
class Test:
x = MyDecriptor()
t = Test()
t.x
# __get__ <__main__.MyDecriptor object at 0x000000CEAAEB6B00> <__main__.Test object at 0x000000CEABDC0898> <class '__main__.Test'>
t.x = 'x-man'
# __set__ <__main__.MyDecriptor object at 0x00000023687C6B00> <__main__.Test object at 0x00000023696B0940> x-man
del t.x
# __delete__ <__main__.MyDecriptor object at 0x000000EC9B160A90> <__main__.Test object at 0x000000EC9B160B38>
__get__ <__main__.MyDecriptor object at 0x0000022008242668> <__main__.Test object at 0x00000220082427B8> <class '__main__.Test'> __set__ <__main__.MyDecriptor object at 0x0000022008242668> <__main__.Test object at 0x00000220082427B8> x-man __delete__ <__main__.MyDecriptor object at 0x0000022008242668> <__main__.Test object at 0x00000220082427B8>
基本的魔法方法就介绍到这里啦。