Python day5 --------递归、匿名函数、高阶函数、内置函数

时间:2022-09-08 07:55:57

一、递归

在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。

递归要求:

1. 必须有一个明确的结束条件

2. 每次进入更深一层递归时,问题规模相比上次递归都应有所减少

3. 递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出)

 def calc(n):
print(n)
if int(n/2) ==0:
return n
return calc(int(n/2)) calc(10) 输出:
10
5
2
1

二、匿名函数(lambda)

匿名函数就是不需要显式的指定函数

 def calc(n):
return n**n
print(calc(10)) #换成匿名函数
calc = lambda n:n**n
print(calc(10))

例子:

 res = map(lambda x:x**2,[1,5,7,4,8])
for i in res:
print(i) >>输出
1
25
49
16
64

三、高阶函数

变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。

 def add(x,y,f):
return f(x) + f(y) res = add(3,-6,abs)
print(res)

四、内置参数

Python day5 --------递归、匿名函数、高阶函数、内置函数


数学运算(7)


1.abs():求数值的绝对值

2.divmod:返回商和余数

divmod(5,2)

>>(2,1)

3.max:返回可迭代对象中的元素中的最大值或者所有参数的最大值

 max(1,2,3) # 传入3个参数 取3个中较大者
3
max('') # 传入1个可迭代对象,取其最大元素值
''
max(-1,0) # 数值默认去数值较大者
0
max(-1,0,key = abs) # 传入了求绝对值函数,则参数都会进行求绝对值后再取较大者
-1

4.min:返回可迭代对象中的元素中的最小值或者所有参数的最小值

5.pow:返回两个数值的幂运算值或其与指定整数的模值

6.round:对浮点数进行四舍五入求值

 >>> round(1.1314926,1)
1.1
>>> round(1.1314926,5)
1.13149

7.sum:对元素类型是数值的可迭代对象中的每个元素求和

类型转换:(24)

1.bool:根据传入的参数的逻辑值创建一个新的布尔值

 >>> bool() #未传入参数
False
>>> bool(0) #数值0、空序列等值为False
False
>>> bool(1)
True

2.int:根据传入的参数创建一个新的整数

 >>> int() #不传入参数时,得到结果0。
0
>>> int(3)
3
>>> int(3.6)
3

3.float:根据传入的参数创建一个新的浮点数

 >>> float() #不提供参数的时候,返回0.0
0.0
>>> float(3)
3.0
>>> float('')
3.0

4.complex:根据传入参数创建一个新的复数

 >>> complex() #当两个参数都不提供时,返回复数 0j。
0j
>>> complex('1+2j') #传入字符串创建复数
(1+2j)
>>> complex(1,2) #传入数值创建复数
(1+2j)

5.str:返回一个对象的字符串表现形式(给用户)

 >>> str()
''
>>> str(None)
'None'
>>> str('abc')
'abc'
>>> str(123)
''

6.bytearray:根据传入的参数创建一个新的字节数组

 >>> bytearray('中文','utf-8')
bytearray(b'\xe4\xb8\xad\xe6\x96\x87')

7.bytes:根据传入的参数创建一个新的不可变字节数组

 >>> bytes('中文','utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'

8.memoryview:根据传入的参数创建一个新的内存查看对象

>>> v = memoryview(b'abcefg')
>>> v[1]
98
>>> v[-1]
103

9.ord:返回Unicode字符对应的整数

>>> ord('a')
97

10.chr:返回整数所对应的Unicode字符

>>> chr(97) #参数类型为整数
'a'

11.bin:将整数转换成2进制字符串

>>> bin(3)
'0b11'

12.oct:将整数转化成8进制数字符串

>>> oct(10)
'0o12'

13.hex:将整数转换成16进制字符串

>>> hex(15)
'0xf'

14.tuple:根据传入的参数创建一个新的元组

>>> tuple() #不传入参数,创建空元组
()
>>> tuple('121') #传入可迭代对象。使用其元素创建新的元组
('1', '2', '1')

15.list:根据传入的参数创建一个新的列表

>>>list() # 不传入参数,创建空列表
[]
>>> list('abcd') # 传入可迭代对象,使用其元素创建新的列表
['a', 'b', 'c', 'd']

16.dict:根据传入的参数创建一个新的字典

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> dict() # 不传入任何参数时,返回空字典。
{}
>>> dict(a = 1,b = 2) # 可以传入键值对创建字典。
{'b': 2, 'a': 1}
>>> dict(zip(['a','b'],[1,2])) # 可以传入映射函数创建字典。
{'b': 2, 'a': 1}
>>> dict((('a',1),('b',2))) # 可以传入可迭代对象创建字典。
{'b': 2, 'a': 1}
Python day5 --------递归、匿名函数、高阶函数、内置函数

17.set:根据传入的参数创建一个新的集合

>>>set() # 不传入参数,创建空集合
set()
>>> a = set(range(10)) # 传入可迭代对象,创建集合
>>> a
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

18.frozenset:根据传入的参数创建一个新的不可变集合

>>> a = frozenset(range(10))
>>> a
frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})

19.enumerate:根据可迭代对象创建枚举对象

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) #指定起始值
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

20.range:根据传入的参数创建一个新的range对象

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> a = range(10)
>>> b = range(1,10)
>>> c = range(1,10,3)
>>> a,b,c # 分别输出a,b,c
(range(0, 10), range(1, 10), range(1, 10, 3))
>>> list(a),list(b),list(c) # 分别输出a,b,c的元素
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 4, 7])
>>>
Python day5 --------递归、匿名函数、高阶函数、内置函数

21.iter:根据传入的参数创建一个新的可迭代对象

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> a = iter('abcd') #字符串序列
>>> a
<str_iterator object at 0x03FB4FB0>
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
next(a)
StopIteration
Python day5 --------递归、匿名函数、高阶函数、内置函数

22.slice:根据传入的参数创建一个新的切片对象

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> c1 = slice(5) # 定义c1
>>> c1
slice(None, 5, None)
>>> c2 = slice(2,5) # 定义c2
>>> c2
slice(2, 5, None)
>>> c3 = slice(1,10,3) # 定义c3
>>> c3
slice(1, 10, 3)
Python day5 --------递归、匿名函数、高阶函数、内置函数

23.super:根据传入的参数创建一个新的子类和父类关系的代理对象

Python day5 --------递归、匿名函数、高阶函数、内置函数
#定义父类A
>>> class A(object):
def __init__(self):
print('A.__init__') #定义子类B,继承A
>>> class B(A):
def __init__(self):
print('B.__init__')
super().__init__() #super调用父类方法
>>> b = B()
B.__init__
A.__init__
Python day5 --------递归、匿名函数、高阶函数、内置函数

24.object:创建一个新的object对象

 >>> a = object()
>>> a.name = 'kim' # 不能设置属性
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
a.name = 'kim'
AttributeError: 'object' object has no attribute 'name'

序列操作:(8)

1.all:判断可迭代对象的每个元素是否都为True值

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> all([1,2]) #列表中每个元素逻辑值均为True,返回True
True
>>> all([0,1,2]) #列表中0的逻辑值为False,返回False
False
>>> all(()) #空元组
True
>>> all({}) #空字典
True
Python day5 --------递归、匿名函数、高阶函数、内置函数

2.any:判断可迭代对象的元素是否有为True值的元素

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> any([0,1,2]) #列表元素有一个为True,则返回True
True
>>> any([0,0]) #列表元素全部为False,则返回False
False
>>> any([]) #空列表
False
>>> any({}) #空字典
False
Python day5 --------递归、匿名函数、高阶函数、内置函数

3.filter:使用指定方法过滤可迭代对象的元素

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> a = list(range(1,10)) #定义序列
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def if_odd(x): #定义奇数判断函数
return x%2==1 >>> list(filter(if_odd,a)) #筛选序列中的奇数
[1, 3, 5, 7, 9]
Python day5 --------递归、匿名函数、高阶函数、内置函数

4.map:使用指定方法去作用传入的每个可迭代对象的元素,生成新的可迭代对象

>>> a = map(ord,'abcd')
>>> a
<map object at 0x03994E50>
>>> list(a)
[97, 98, 99, 100]

5.next:返回可迭代对象中的下一个元素值

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> a = iter('abcd')
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
next(a)
StopIteration #传入default参数后,如果可迭代对象还有元素没有返回,则依次返回其元素值,如果所有元素已经返回,则返回default指定的默认值而不抛出StopIteration 异常
>>> next(a,'e')
'e'
>>> next(a,'e')
'e'
Python day5 --------递归、匿名函数、高阶函数、内置函数

6.reversed:反转序列生成新的可迭代对象

>>> a = reversed(range(10)) # 传入range对象
>>> a # 类型变成迭代器
<range_iterator object at 0x035634E8>
>>> list(a)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

7.sorted:对可迭代对象进行排序,返回一个新的列表

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> a = ['a','b','d','c','B','A']
>>> a
['a', 'b', 'd', 'c', 'B', 'A'] >>> sorted(a) # 默认按字符ascii码排序
['A', 'B', 'a', 'b', 'c', 'd'] >>> sorted(a,key = str.lower) # 转换成小写后再排序,'a'和'A'值一样,'b'和'B'值一样
['a', 'A', 'b', 'B', 'c', 'd']
Python day5 --------递归、匿名函数、高阶函数、内置函数

8.zip:聚合传入的每个迭代器中相同位置的元素,返回一个新的元组类型迭代器

>>> x = [1,2,3] #长度3
>>> y = [4,5,6,7,8] #长度5
>>> list(zip(x,y)) # 取最小长度3
[(1, 4), (2, 5), (3, 6)]

对象操作:(9)

1.help:返回对象的帮助信息

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> help(str)
Help on class str in module builtins: class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
***************************
Python day5 --------递归、匿名函数、高阶函数、内置函数

2.dir:返回对象或者当前作用域内的属性列表

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> import math
>>> math
<module 'math' (built-in)>
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
Python day5 --------递归、匿名函数、高阶函数、内置函数

3.id:返回对象的唯一标识符

>>> a = 'some text'
>>> id(a)
69228568

4.hash:获取对象的哈希值

>>> hash('good good study')
1032709256

5.type:返回对象的类型,或者根据传入的参数创建一个新的类型

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> type(1) # 返回对象的类型
<class 'int'> #使用type函数创建类型D,含有属性InfoD
>>> D = type('D',(A,B),dict(InfoD='some thing defined in D'))
>>> d = D()
>>> d.InfoD
'some thing defined in D'
Python day5 --------递归、匿名函数、高阶函数、内置函数

6.len:返回对象的长度

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> len('abcd') # 字符串
>>> len(bytes('abcd','utf-8')) # 字节数组
>>> len((1,2,3,4)) # 元组
>>> len([1,2,3,4]) # 列表
>>> len(range(1,5)) # range对象
>>> len({'a':1,'b':2,'c':3,'d':4}) # 字典
>>> len({'a','b','c','d'}) # 集合
>>> len(frozenset('abcd')) #不可变集合
Python day5 --------递归、匿名函数、高阶函数、内置函数

7.ascii:返回对象的可打印表字符串表现方式

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> ascii(1)
'1'
>>> ascii('&')
"'&'"
>>> ascii(9000000)
'9000000'
>>> ascii('中文') #非ascii字符
"'\\u4e2d\\u6587'"
Python day5 --------递归、匿名函数、高阶函数、内置函数

8.format:格式化显示值

Python day5 --------递归、匿名函数、高阶函数、内置函数
#字符串可以提供的参数 's' None
>>> format('some string','s')
'some string'
>>> format('some string')
'some string' #整形数值可以提供的参数有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None
>>> format(3,'b') #转换成二进制
'11'
>>> format(97,'c') #转换unicode成字符
'a'
>>> format(11,'d') #转换成10进制
'11'
>>> format(11,'o') #转换成8进制
'13'
>>> format(11,'x') #转换成16进制 小写字母表示
'b'
>>> format(11,'X') #转换成16进制 大写字母表示
'B'
>>> format(11,'n') #和d一样
'11'
>>> format(11) #默认和d一样
'11' #浮点数可以提供的参数有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None
>>> format(314159267,'e') #科学计数法,默认保留6位小数
'3.141593e+08'
>>> format(314159267,'0.2e') #科学计数法,指定保留2位小数
'3.14e+08'
>>> format(314159267,'0.2E') #科学计数法,指定保留2位小数,采用大写E表示
'3.14E+08'
>>> format(314159267,'f') #小数点计数法,默认保留6位小数
'314159267.000000'
>>> format(3.14159267000,'f') #小数点计数法,默认保留6位小数
'3.141593'
>>> format(3.14159267000,'0.8f') #小数点计数法,指定保留8位小数
'3.14159267'
>>> format(3.14159267000,'0.10f') #小数点计数法,指定保留10位小数
'3.1415926700'
>>> format(3.14e+1000000,'F') #小数点计数法,无穷大转换成大小字母
'INF' #g的格式化比较特殊,假设p为格式中指定的保留小数位数,先尝试采用科学计数法格式化,得到幂指数exp,如果-4<=exp<p,则采用小数计数法,并保留p-1-exp位小数,否则按小数计数法计数,并按p-1保留小数位数
>>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点
'3e-05'
>>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留1位小数点
'3.1e-05'
>>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留2位小数点
'3.14e-05'
>>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点,E使用大写
'3.14E-05'
>>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留0位小数点
'3'
>>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留1位小数点
'3.1'
>>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留2位小数点
'3.14'
>>> format(0.00003141566,'.1n') #和g相同
'3e-05'
>>> format(0.00003141566,'.3n') #和g相同
'3.14e-05'
>>> format(0.00003141566) #和g相同
'3.141566e-05'
Python day5 --------递归、匿名函数、高阶函数、内置函数

9.vars:返回当前作用域内的局部变量和其值组成的字典,或者返回对象的属性列表

Python day5 --------递归、匿名函数、高阶函数、内置函数
#作用于类实例
>>> class A(object):
pass >>> a.__dict__
{}
>>> vars(a)
{}
>>> a.name = 'Kim'
>>> a.__dict__
{'name': 'Kim'}
>>> vars(a)
{'name': 'Kim'}
Python day5 --------递归、匿名函数、高阶函数、内置函数

反射操作:(8)

1.__import__:动态导入模块

index = __import__('index')
index.sayHello()

2.isinstance:判断对象是否是类或者类型元组中任意类元素的实例

>>> isinstance(1,int)
True
>>> isinstance(1,str)
False
>>> isinstance(1,(int,str))
True

3.issubclass:判断类是否是另外一个类或者类型元组中任意类元素的子类

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> issubclass(bool,int)
True
>>> issubclass(bool,str)
False >>> issubclass(bool,(str,int))
True
Python day5 --------递归、匿名函数、高阶函数、内置函数

4.hasattr:检查对象是否含有属性

Python day5 --------递归、匿名函数、高阶函数、内置函数
#定义类A
>>> class Student:
def __init__(self,name):
self.name = name >>> s = Student('Aim')
>>> hasattr(s,'name') #a含有name属性
True
>>> hasattr(s,'age') #a不含有age属性
False
Python day5 --------递归、匿名函数、高阶函数、内置函数

5.getattr:获取对象的属性值

Python day5 --------递归、匿名函数、高阶函数、内置函数
#定义类Student
>>> class Student:
def __init__(self,name):
self.name = name >>> getattr(s,'name') #存在属性name
'Aim' >>> getattr(s,'age',6) #不存在属性age,但提供了默认值,返回默认值 >>> getattr(s,'age') #不存在属性age,未提供默认值,调用报错
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
getattr(s,'age')
AttributeError: 'Stduent' object has no attribute 'age'
Python day5 --------递归、匿名函数、高阶函数、内置函数

6.setattr:设置对象的属性值

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> class Student:
def __init__(self,name):
self.name = name >>> a = Student('Kim')
>>> a.name
'Kim'
>>> setattr(a,'name','Bob')
>>> a.name
'Bob'
Python day5 --------递归、匿名函数、高阶函数、内置函数

7.delattr:删除对象的属性

Python day5 --------递归、匿名函数、高阶函数、内置函数
#定义类A
>>> class A:
def __init__(self,name):
self.name = name
def sayHello(self):
print('hello',self.name) #测试属性和方法
>>> a.name
'小麦'
>>> a.sayHello()
hello 小麦 #删除属性
>>> delattr(a,'name')
>>> a.name
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
a.name
AttributeError: 'A' object has no attribute 'name'
Python day5 --------递归、匿名函数、高阶函数、内置函数

8.callable:检测对象是否可被调用

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> class B: #定义类B
def __call__(self):
print('instances are callable now.') >>> callable(B) #类B是可调用对象
True
>>> b = B() #调用类B
>>> callable(b) #实例b是可调用对象
True
>>> b() #调用实例b成功
instances are callable now.
Python day5 --------递归、匿名函数、高阶函数、内置函数

变量操作:(2)

1.globals:返回当前作用域内的全局变量和其值组成的字典

>>> globals()
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
>>> a = 1
>>> globals() #多了一个a
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, 'a': 1, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}

2.locals:返回当前作用域内的局部变量和其值组成的字典

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> def f():
print('before define a ')
print(locals()) #作用域内无变量
a = 1
print('after define a')
print(locals()) #作用域内有一个a变量,值为1 >>> f
<function f at 0x03D40588>
>>> f()
before define a
{}
after define a
{'a': 1}
Python day5 --------递归、匿名函数、高阶函数、内置函数

交互操作:(2)

1.print:向标准输出对象打印输出

>>> print(1,2,3)
1 2 3
>>> print(1,2,3,sep = '+')
1+2+3
>>> print(1,2,3,sep = '+',end = '=?')
1+2+3=?

2.input:读取用户输入值

>>> s = input('please input your name:')
please input your name:Ain
>>> s
'Ain'

文件操作:(1)

1.open:使用指定的模式和编码打开文件,返回文件读写对象

# t为文本读写,b为二进制读写
>>> a = open('test.txt','rt')
>>> a.read()
'some text'
>>> a.close()

编译执行:(4)

compile:将字符串编译为代码或者AST对象,使之能够通过exec语句来执行或者eval进行求值

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> #流程语句使用exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec')
>>> exec (compile1)
0
1
2
3
4
5
6
7
8
9 >>> #简单求值表达式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2)
10
Python day5 --------递归、匿名函数、高阶函数、内置函数

2.eval:执行动态表达式求值

>>> eval('1+2+3+4')
10

3.exec:执行动态语句块

>>> exec('a=1+2') #执行语句
>>> a
3

4.repr:返回一个对象的字符串表现形式(给解释器)

>>> a = 'some text'
>>> str(a)
'some text'
>>> repr(a)
"'some text'"

装饰器:(3)

1.property:标示属性的装饰器

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> class C:
def __init__(self):
self._name = ''
@property
def name(self):
"""i'm the 'name' property."""
return self._name
@name.setter
def name(self,value):
if value is None:
raise RuntimeError('name can not be None')
else:
self._name = value >>> c = C() >>> c.name # 访问属性
''
>>> c.name = None # 设置属性时进行验证
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
c.name = None
File "<pyshell#81>", line 11, in name
raise RuntimeError('name can not be None')
RuntimeError: name can not be None >>> c.name = 'Kim' # 设置属性
>>> c.name # 访问属性
'Kim' >>> del c.name # 删除属性,不提供deleter则不能删除
Traceback (most recent call last):
File "<pyshell#87>", line 1, in <module>
del c.name
AttributeError: can't delete attribute
>>> c.name
'Kim'
Python day5 --------递归、匿名函数、高阶函数、内置函数

2.classmethod:标示方法为类方法的装饰器

Python day5 --------递归、匿名函数、高阶函数、内置函数
>>> class C:
@classmethod
def f(cls,arg1):
print(cls)
print(arg1) >>> C.f('类对象调用类方法')
<class '__main__.C'>
类对象调用类方法 >>> c = C()
>>> c.f('类实例对象调用类方法')
<class '__main__.C'>
类实例对象调用类方法
Python day5 --------递归、匿名函数、高阶函数、内置函数

3.staticmethod:标示方法为静态方法的装饰器

Python day5 --------递归、匿名函数、高阶函数、内置函数
# 使用装饰器定义静态方法
>>> class Student(object):
def __init__(self,name):
self.name = name
@staticmethod
def sayHello(lang):
print(lang)
if lang == 'en':
print('Welcome!')
else:
print('你好!') >>> Student.sayHello('en') #类调用,'en'传给了lang参数
en
Welcome! >>> b = Student('Kim')
>>> b.sayHello('zh') #类实例对象调用,'zh'传给了lang参数
zh
你好

Python day5 --------递归、匿名函数、高阶函数、内置函数的更多相关文章

  1. Python【map、reduce、filter】内置函数使用说明&lpar;转载&rpar;

    转自:http://www.blogjava.net/vagasnail/articles/301140.html?opt=admin 介绍下Python 中 map,reduce,和filter 内 ...

  2. Python【map、reduce、filter】内置函数使用说明

    题记 介绍下Python 中 map,reduce,和filter 内置函数的方法 一:map map(...) map(function, sequence[, sequence, ...]) -& ...

  3. &lbrack;JSP&rsqb;&lbrack;JSTL&rsqb;页面调用函数--它&dollar;&lbrace;fn:&rcub;内置函数、是推断字符串是空的、更换车厢

    页面中调用函数--之${fn:}内置函数 函数描写叙述 fn:contains(string, substring) 假设參数string中包括參数substring,返回true fn:contai ...

  4. Python之旅Day3 文件操作 函数(递归&vert;匿名&vert;嵌套&vert;高阶)函数式编程 内置方法

    知识回顾 常见五大数据类型分类小结:数字.字符串.列表.元组.字典 按存值个数区分:容器类型(列表.字典.元组) 标量原子(数字.字符串) 按是否可变区分:可变(列表.字典) 不可变(数字.字符串.元 ...

  5. python基础--递归、三元表达式、列表&lpar;字典&rpar;生成式、匿名函数、常用的内置函数

    函数的递归:函数在调用阶段直接或者间接的又调用自身 递归的两个阶段: 1.回溯:就是一次次重复的过程,这个重复的过程必须建立在每一次重复问题的复杂度都是应该下降的,直接有一个最终的结束条件(这个结束条 ...

  6. 跟着ALEX 学python day3集合 文件操作 函数和函数式编程 内置函数

    声明 : 文档内容学习于 http://www.cnblogs.com/xiaozhiqi/  一. 集合 集合是一个无序的,不重复的数据组合,主要作用如下 1.去重 把一个列表变成集合 ,就自动去重 ...

  7. scoping作用域,anonymous function匿名函数,built-in functions内置函数

    作用域练习1 def test1(): print('in the test1') def test(): print('in the test') return test1 res = test() ...

  8. Python 4 函数的参数,内置函数&comma;装饰器,生成器,迭代器,

    一.函数的参数: 1.位置参数:调用函数时根据函数定义的参数位置来传递参数. 2.关键字参数:用于函数调用,通过“键-值”形式加以指定.可以让函数更加清晰.容易使用,同时也清除了参数的顺序需求. 3. ...

  9. python基础学习之函数基础和部分内置函数

    在函数调用的时候,必备参数必须要传入 函数定义: def  函数名: 代码块pass return  返回值 函数名命名规则: 字母.数字和下划线组成,和变量命名规则一致 pass在这里表示什么都没有 ...

  10. day16 函数的用法:内置函数,匿名函数

    思维导图需要补全 : 一共有68个内置函数: #内置:python自带 # def func(): # a = 1 # b = 2 # print(locals()) # print(globals( ...

随机推荐

  1. C&num; 创建文件时,文件夹不存在,如何自动创建文件夹

    c# 创建文件时怎么创建文件夹?strhtml=......StreamWriter sw=new StreamWriter("D:/test/1.aspx",false);sw. ...

  2. android蓝牙&lpar;二&rpar;——接收数据

    在蓝牙开发中,我们有这种一个需求:我们的androidclient要始终保持和蓝牙的连接,当蓝牙有数据返回的时候,androidclient就要及时的收取数据,当蓝牙没有数据返回的时候我们就要保持an ...

  3. 小程序 切换到tabBar页面不刷新问题

    小程序跳转的几种方式有wx.navigateTo,wx.redirectTo,wx.reLaunch,wx.switchTab等.下面我们重点研究切换到tabBar的两种方式. wx.switchTa ...

  4. Angular2入门:TypeScript的类型 - 对象解构

  5. 【js基础】创建对象的几种常见模式(工厂模式,构造函数模式,原型模式,构造原型组合模式)

    一.工厂模式 缺点:没有解决对象识别的问题 优点:解决了创建多个相似对象的问题 function createPerson(name,age,job){ var o = new Object(); o ...

  6. python第二天 列表、元组

    今天学习了列表.元组相关的知识:与C中的数组列表相似,元组为只读列表: 以及切片相关操作: #!usr/bin/env python #-*-coding:utf-8-*- # Author calm ...

  7. androidpn 推送系统

    (文中部分内容来自网络,如无意中侵犯了版权,请告之!) XMPP协议: XMPP : The Extensible Messaging andPresence Protocol. 中文全称:可扩展通讯 ...

  8. LeetCode--232--用栈实现队列

    问题描述: 使用栈实现队列的下列操作: push(x) -- 将一个元素放入队列的尾部. pop() -- 从队列首部移除元素. peek() -- 返回队列首部的元素. empty() -- 返回队 ...

  9. c&plus;&plus; 查找容器中不满足条件的元素,返回iterator(find&lowbar;if&lowbar;not)

    #include <iostream> // std::cout #include <algorithm> // std::find_if_not #include <a ...

  10. 【bzoj1441】Min 扩展裴蜀定理

    题目描述 给出n个数(A1...An)现求一组整数序列(X1...Xn)使得S=A1*X1+...An*Xn>0,且S的值最小 输入 第一行给出数字N,代表有N个数 下面一行给出N个数 输出 S ...