1.def
在Python中,定义一个函数需要使用 def 语句,def 后写出函数名、括号、参数和冒号:,然后在缩进块中编写函数体,函数返回值用return语句返回。
#def
def test_func(data):
if(data):
print(data)
else:
print('NULL')
test_func('hello')
test_func(0)
结果:
hello
NULL
2.pass
pass是一个空指令,当定义了一个函数,但是又没有想好要写什么内容,可以在函数中直接写pass,让整个代码先跑起来。在一些判断语句中pass也同样适用。
#函数
def test_func2(data):
pass
#判断
if data > 0:
pass
3.isinstance
isinstance的意思是“判断类型”,是一个内置函数,用于判断一个对象是否是一个已知的类型。返回结果为Bool类型。
def test_func(data):
if not isinstance(data,(int,float)):
print("false type")
test_func('hello')
结果:false type
4.raise
很多时候需要在程序中添加异常报警。比如对类型判断的时候,如果类型出错,只是打印一句LOG是非常不明显的。此时就可以使用raise语句来抛出异常。
def test_func(data):
if not isinstance(data,(int,float)):
raise TypeError('false type')
test_func('hello')
结果:
Traceback (most recent call last):
File "d:/python/test_project/test.py", line 21, in <module>
test_func('hello')
File "d:/python/test_project/test.py", line 9, in test_func
raise TypeError('false type')
TypeError: false type
这里TypeError是系统内置的异常类型,还有其他很多的类型,可以根据需求自己选择。
class SystemError(_StandardError): ...
class TypeError(_StandardError): ...
class ValueError(_StandardError): ...
class FloatingPointError(ArithmeticError): ...
class OverflowError(ArithmeticError): ...
class ZeroDivisionError(ArithmeticError): ...
class ModuleNotFoundError(ImportError): ...
class IndexError(LookupError): ...
class KeyError(LookupError): ...
class UnboundLocalError(NameError): ...
class BlockingIOError(OSError):
characters_written: int
class ChildProcessError(OSError): ...
class ConnectionError(OSError): ...
class BrokenPipeError(ConnectionError): ...
class ConnectionAbortedError(ConnectionError): ...
class ConnectionRefusedError(ConnectionError): ...
class ConnectionResetError(ConnectionError): ...
class FileExistsError(OSError): ...
class FileNotFoundError(OSError): ...
class InterruptedError(OSError): ...
class IsADirectoryError(OSError): ...
class NotADirectoryError(OSError): ...
class PermissionError(OSError): ...
class ProcessLookupError(OSError): ...
class TimeoutError(OSError): ...
class NotImplementedError(RuntimeError): ...
class RecursionError(RuntimeError): ...
class IndentationError(SyntaxError): ...
class TabError(IndentationError): ...
class UnicodeError(ValueError): ...
当然,也可以不设置异常类型。
def test_func(data):
if not isinstance(data,(int,float)):
raise
test_func('hello')
结果:
Traceback (most recent call last):
File "d:/python/test_project/test.py", line 22, in <module>
test_func('hello')
File "d:/python/test_project/test.py", line 10, in test_func
raise
RuntimeError: No active exception to reraise
5.可变参数
如果有一个函数可能会传入多个参数,但是又不确定参数的个数是多少,此时就可以使用可变参数。可变参数允许传入的参数个数为0个。
def test_func(*data):
for n in data:
print(n)
test_func('hello','world',"this","is")
结果:
hello
world
this
is
如果此时有一个list或tuple需要传入函数中,也可以使用可变参数来实现。
def test_func(*data):
for n in data:
print(n)
temp = ['this','is','a','test']
test_func(*temp)
结果:
this
is
a
test
6.关键字参数
关键字参数允许传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装成一个dict。
def personal_inf(**inf):
print(inf)
personal_inf(name = 'json', age=18)
结果:
{'name': 'json', 'age': 18}
7.命名关键字参数
对于关键字参数,函数调用者可以传入任意个数的关键字参数,对于需要的参数,可以在函数中自行判断。例如
def personal_inf(**inf):
if 'name' in inf:
print('name is %s' %inf['name'])
if 'age' in inf:
print('age is %s' %inf['age'])
personal_inf(age=18,city='beijing')
结果:
age is 18
如果需要对参数的关键字进行限制的话,就需要用到命名关键字参数。命名关键字参数需要一个特殊分割符 ‘ * ’ ,' * ' 后面的参数被视为命名关键字参数。
def personal_inf(*,name,age):
print(name,age)
personal_inf(name='json',age=18)
结果:
json 18
如果此时输入的参数不是需要的参数的话。
def personal_inf(*,name,age):
print(name,age)
personal_inf(name='json',age=18,city='beijing')
编译就会报错
Traceback (most recent call last):
File "d:/python/test_project/test.py", line 18, in <module>
personal_inf(name='json',age=18,city='beijing')
TypeError: personal_inf() got an unexpected keyword argument 'city'
8.map
map()函数接收两个参数,一个是函数,一个是Iterator,Iterator是惰性序列,因此通过List()函数让他把整个序列都计算出来并返回一个list。
def t_lower(a):
return a.lower()
tl = {'HELLO','WORLD',"THIS","IS"}
tl2 = list(map(t_lower,['HELLO','WORLD',"THIS","IS"])) #将所有元素通过t_lower函数转为小写,并最终通过list()函数转换为list
print(tl2)
结果:
['hello', 'world', 'this', 'is']
9.reduce
reduce()函数接收两个参数,一个是函数,一个是序列。reduce把结果继续和下一个元素做累积计算。
def t_sum(a, b):
return a+b
tl = {1,2,3,4,5,6,7,8,9,10}
print(reduce(t_sum,tl)) #计算累加和
结果:
55
10.filter
filter是一个内建的函数,用于过滤序列。接收两个参数,一个函数,一个序列。filter()把传入的函数一次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。注意,filter()函数返回的是一个Iterator惰性序列,所以要用list函数获取所有结果并返回list。
strip方法
strip方法用于移除字符串头、尾指定的字符(默认是空格或换行符)或字符序列。
注意:该方法只能删除开头或结尾的字符,不能删除中间部分的字符。
tl2 = "000012345678900000"
print(tl2.strip('0')) #过滤头和尾的0
结果:
123456789
strip能过滤字符串,当然也能过滤List中的元素字符串,比如可以过滤List中的空元素。
def filter_empty(a):
return a and a.strip() #默认过滤空
tl = ['',None,'a','b','','c',None,'d']
print(list(filter(filter_empty,tl)))
结果:
['a', 'b', 'c', 'd']
11.sorted
sorted是一个自动排序的函数,该函数是一个高阶函数,可以接受一个Key函数来实现自定义的排序。
tl = [10,8,6,4,2,1,3,5,7,9] #排序
print(sorted(tl))
结果:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def t_square(a):
return a*a
tl = [-10,8,-6,4,-2,1,-3,5,-7,9]
print(sorted(tl,key=t_square)) #对比元素的平方后进行排序
结果:
[1, -2, -3, 4, 5, -6, -7, 8, 9, -10]
12.hasattr
该函数用于判断某个对象中,是否存在指定的属性名。存在返回True,否则,返回False
第一个参数:对象。
第二个参数:属性名
class human:
def __init__(self) -> None:#初始化
self.name = 'xiaoming'
self.age = 18
self.city = 'shanghai'
print(hasattr(p,'name'))
print(hasattr(p,'age'))
print(hasattr(p,'gender'))
结果:
True
True
False
13.getattr
返回对象对应的属性(第二个参数指定的属性),当只有两个参数时,若不存在,则报错。三个参数时,若不存在,则返回第三个参数设置的默认值。
第一个参数:对象
第二个参数:属性
第三个参数:报错值
class human:
def __init__(self) -> None:#初始化
self.name = 'xiaoming'
self.age = 18
self.city = 'shanghai'
print(getattr(p,'name'))
print(getattr(p,'gender'))
print(getattr(p,'gender',-2))
结果:
xiaoming
Traceback (most recent call last): #只有两个参数,报错
File "d:/python/test_project/test.py", line 78, in <module>
print(getattr(p,'gender')) #实例
AttributeError: 'human' object has no attribute 'gender'
-2 #有三个参数,返回第三个参数的值
14.setattr
设置对象的指定属性内容。如果当前设置的属性不存在,则创建该属性。
第一个参数:对象
第二个参数:属性名
第三个参数:属性值
class human:
def __init__(self) -> None:#初始化
self.name = 'xiaoming'
self.age = 18
self.city = 'shanghai'
print(getattr(p,'name'))
setattr(p,'name','lisa') #修改属性值
print(getattr(p,'name'))
print(getattr(p,'gender',-1)) #获取不存在的属性
setattr(p,'gender','boy') #该属性不存在,则创建属性
print(p.gender)
结果:
xiaoming
lisa
-1
boy
15.delattr
删除属性,如果没有该属性,则直接报错
class human:
def __init__(self) -> None:#初始化
self.name = 'xiaoming'
self.age = 18
self.city = 'shanghai'
print(getattr(p,'name'))
delattr(p,'name') #删除属性
print(getattr(p,'name',-1))
结果:
xiaoming
-1
16.动态操作属性
可以通过用户输入的方式来实现动态添加属性。
class human:
def __init__(self) -> None:#初始化
self.name = 'xiaoming'
self.age = 18
self.city = 'shanghai'
p = human() #实例
attr = input('请输入要添加的属性名:')
attr_value = input('请输入要添加的属性值:')
setattr(p,attr,attr_value) #添加属性
print('您添加的属性名为:%s,属性值为:%s' %(attr,getattr(p,attr,-1)))
结果:
请输入要添加的属性名:height
请输入要添加的属性值:180
您添加的属性名为:height,属性值为:180