python内置函数有哪些

python内置函数有:abs、divmod、max、min、pow、round、sum、bool、int、float、complex、str、bytearray、bytes、memoryview、ord、oct、tuple、map等等。

python内置函数有哪些

本教程操作环境:windows7系统、Python3版、Dell G3电脑。

内置函数分类:

  • 数学运算(7个)

  • 类型转换(24个)

  • 序列操作(8个)

  • 对象操作(7个)

  • 反射操作(8个)

  • 变量操作(2个)

  • 交互操作(2个)

  • 文件操作(1个)

  • 编译执行(4个)

  • 装饰器(3个)

数学运算

abs:求数值的绝对值

>>> abs(-2)
2

pmod:返回两个数值的商和余数

>>> pmod(5,2)
(2, 1)
>> pmod(5.5,2)
(2.0, 1.5)

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

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

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

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

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

>>> pow(2,3)
>>> 2**3

>>> pow(2,3,5)
>>> pow(2,3)%5

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

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

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

# 传入可迭代对象
>>> sum((1,2,3,4))
10
# 元素类型必须是数值型
>>> sum((1.5,2.5,3.5,4.5))
12.0
>>> sum((1,2,3,4),-10)
0

类型转换

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

>>> ord('a')
97

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

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

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

>>> bin(3) 
'0b11'

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

>>> oct(10)
'0o12'

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

>>> hex(15)
'0xf'

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

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

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

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

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

>>> 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}

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

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

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

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

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')]

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

>>> 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])
>>>

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

>>> a = iter('abcd') #字符串序列
>>> a
<str_iterator object at 0x03FB4FB0>
>>> next(a)
&#39;a&#39;
>>> next(a)
&#39;b&#39;
>>> next(a)
&#39;c&#39;
>>> next(a)
&#39;d&#39;
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    next(a)
StopIteration

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

>>> 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)

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

#定义父类A
>>> class A(object):
    def __init__(self):
        print(&#39;A.__init__&#39;)

#定义子类B,继承A
>>> class B(A):
    def __init__(self):
        print(&#39;B.__init__&#39;)
        super().__init__()

#super调用父类方法
>>> b = B()
B.__init__
A.__init__

object:创建一个新的object对象

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

序列操作

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

>>> all([1,2]) #列表中每个元素逻辑值均为True,返回True
True
>>> all([0,1,2]) #列表中0的逻辑值为False,返回False
False
>>> all(()) #空元组
True
>>> all({}) #空字典
True

any:判断可迭代对象的元素是否有为True值的元素>>> any([0,1,2]) #列表元素有一个为True,则返回True

True
>>> any([0,0]) #列表元素全部为False,则返回False
False
>>> any([]) #空列表
False
>>> any({}) #空字典
False

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

>>> 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]

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

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

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

>>> a = iter(&#39;abcd&#39;)
>>> next(a)
&#39;a&#39;
>>> next(a)
&#39;b&#39;
>>> next(a)
&#39;c&#39;
>>> next(a)
&#39;d&#39;
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    next(a)
StopIteration

#传入default参数后,如果可迭代对象还有元素没有返回,则依次返回其元素值,如果所有元素已经返回,则返回default指定的默认值而不抛出StopIteration 异常
>>> next(a,&#39;e&#39;)
&#39;e&#39;
>>> next(a,&#39;e&#39;)
&#39;e&#39;

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

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

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

>>> a = [&#39;a&#39;,&#39;b&#39;,&#39;d&#39;,&#39;c&#39;,&#39;B&#39;,&#39;A&#39;]
>>> a
[&#39;a&#39;, &#39;b&#39;, &#39;d&#39;, &#39;c&#39;, &#39;B&#39;, &#39;A&#39;]

>>> sorted(a) # 默认按字符ascii码排序
[&#39;A&#39;, &#39;B&#39;, &#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;]

>>> sorted(a,key = str.lower) # 转换成小写后再排序,&#39;a&#39;和&#39;A&#39;值一样,&#39;b&#39;和&#39;B&#39;值一样
[&#39;a&#39;, &#39;A&#39;, &#39;b&#39;, &#39;B&#39;, &#39;c&#39;, &#39;d&#39;]

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

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

对象操作

help:返回对象的帮助信息

>>> help(str) 
Help on class str in module builtins:

class str(object)
 |  str(object=&#39;&#39;) -> 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 &#39;strict&#39;.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
  ***************************

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

>>> import math
>>> math
<module &#39;math&#39; (built-in)>
>>> dir(math)
[&#39;__doc__&#39;, &#39;__loader__&#39;, &#39;__name__&#39;, &#39;__package__&#39;, &#39;__spec__&#39;, &#39;acos&#39;, &#39;acosh&#39;, &#39;asin&#39;, &#39;asinh&#39;, &#39;atan&#39;, &#39;atan2&#39;, &#39;atanh&#39;, &#39;ceil&#39;, &#39;copysign&#39;, &#39;cos&#39;, &#39;cosh&#39;, &#39;degrees&#39;, &#39;e&#39;, &#39;erf&#39;, &#39;erfc&#39;, &#39;exp&#39;, &#39;expm1&#39;, &#39;fabs&#39;, &#39;factorial&#39;, &#39;floor&#39;, &#39;fmod&#39;, &#39;frexp&#39;, &#39;fsum&#39;, &#39;gamma&#39;, &#39;gcd&#39;, &#39;hypot&#39;, &#39;inf&#39;, &#39;isclose&#39;, &#39;isfinite&#39;, &#39;isinf&#39;, &#39;isnan&#39;, &#39;ldexp&#39;, &#39;lgamma&#39;, &#39;log&#39;, &#39;log10&#39;, &#39;log1p&#39;, &#39;log2&#39;, &#39;modf&#39;, &#39;nan&#39;, &#39;pi&#39;, &#39;pow&#39;, &#39;radians&#39;, &#39;sin&#39;, &#39;sinh&#39;, &#39;sqrt&#39;, &#39;tan&#39;, &#39;tanh&#39;, &#39;trunc&#39;]

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

>>> a = &#39;some text&#39;
>>> id(a)
69228568

hash:获取对象的哈希值

>>> hash(&#39;good good study&#39;)
1032709256

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

>>> type(1) # 返回对象的类型
<class &#39;int&#39;>

#使用type函数创建类型D,含有属性InfoD
>>> D = type(&#39;D&#39;,(A,B),dict(InfoD=&#39;some thing defined in D&#39;))
>>> d = D()
>>> d.InfoD
 &#39;some thing defined in D&#39;

len:返回对象的长度

>>> len(&#39;abcd&#39;) # 字符串
>>> len(bytes(&#39;abcd&#39;,&#39;utf-8&#39;)) # 字节数组
>>> len((1,2,3,4)) # 元组
>>> len([1,2,3,4]) # 列表
>>> len(range(1,5)) # range对象
>>> len({&#39;a&#39;:1,&#39;b&#39;:2,&#39;c&#39;:3,&#39;d&#39;:4}) # 字典
>>> len({&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;}) # 集合
>>> len(frozenset(&#39;abcd&#39;)) #不可变集合

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

>>> ascii(1)
&#39;1&#39;
>>> ascii(&#39;&&#39;)
"&#39;&&#39;"
>>> ascii(9000000)
&#39;9000000&#39;
>>> ascii(&#39;中文&#39;) #非ascii字符
"&#39;\\u4e2d\\u6587&#39;"

format:格式化显示值

#字符串可以提供的参数 &#39;s&#39; None
>>> format(&#39;some string&#39;,&#39;s&#39;)
&#39;some string&#39;
>>> format(&#39;some string&#39;)
&#39;some string&#39;

#整形数值可以提供的参数有 &#39;b&#39; &#39;c&#39; &#39;d&#39; &#39;o&#39; &#39;x&#39; &#39;X&#39; &#39;n&#39; None
>>> format(3,&#39;b&#39;) #转换成二进制
&#39;11&#39;
>>> format(97,&#39;c&#39;) #转换unicode成字符
&#39;a&#39;
>>> format(11,&#39;d&#39;) #转换成10进制
&#39;11&#39;
>>> format(11,&#39;o&#39;) #转换成8进制
&#39;13&#39;
>>> format(11,&#39;x&#39;) #转换成16进制 小写字母表示
&#39;b&#39;
>>> format(11,&#39;X&#39;) #转换成16进制 大写字母表示
&#39;B&#39;
>>> format(11,&#39;n&#39;) #和d一样
&#39;11&#39;
>>> format(11) #默认和d一样
&#39;11&#39;

#浮点数可以提供的参数有 &#39;e&#39; &#39;E&#39; &#39;f&#39; &#39;F&#39; &#39;g&#39; &#39;G&#39; &#39;n&#39; &#39;%&#39; None
>>> format(314159267,&#39;e&#39;) #科学计数法,默认保留6位小数
&#39;3.141593e+08&#39;
>>> format(314159267,&#39;0.2e&#39;) #科学计数法,指定保留2位小数
&#39;3.14e+08&#39;
>>> format(314159267,&#39;0.2E&#39;) #科学计数法,指定保留2位小数,采用大写E表示
&#39;3.14E+08&#39;
>>> format(314159267,&#39;f&#39;) #小数点计数法,默认保留6位小数
&#39;314159267.000000&#39;
>>> format(3.14159267000,&#39;f&#39;) #小数点计数法,默认保留6位小数
&#39;3.141593&#39;
>>> format(3.14159267000,&#39;0.8f&#39;) #小数点计数法,指定保留8位小数
&#39;3.14159267&#39;
>>> format(3.14159267000,&#39;0.10f&#39;) #小数点计数法,指定保留10位小数
&#39;3.1415926700&#39;
>>> format(3.14e+1000000,&#39;F&#39;)  #小数点计数法,无穷大转换成大小字母
&#39;INF&#39;

#g的格式化比较特殊,假设p为格式中指定的保留小数位数,先尝试采用科学计数法格式化,得到幂指数exp,如果-4<=exp<p,则采用小数计数法,并保留p-1-exp位小数,否则按小数计数法计数,并按p-1保留小数位数
>>> format(0.00003141566,&#39;.1g&#39;) #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点
&#39;3e-05&#39;
>>> format(0.00003141566,&#39;.2g&#39;) #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留1位小数点
&#39;3.1e-05&#39;
>>> format(0.00003141566,&#39;.3g&#39;) #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留2位小数点
&#39;3.14e-05&#39;
>>> format(0.00003141566,&#39;.3G&#39;) #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点,E使用大写
&#39;3.14E-05&#39;
>>> format(3.1415926777,&#39;.1g&#39;) #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留0位小数点
&#39;3&#39;
>>> format(3.1415926777,&#39;.2g&#39;) #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留1位小数点
&#39;3.1&#39;
>>> format(3.1415926777,&#39;.3g&#39;) #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留2位小数点
&#39;3.14&#39;
>>> format(0.00003141566,&#39;.1n&#39;) #和g相同
&#39;3e-05&#39;
>>> format(0.00003141566,&#39;.3n&#39;) #和g相同
&#39;3.14e-05&#39;
>>> format(0.00003141566) #和g相同
&#39;3.141566e-05&#39;

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

#作用于类实例
>>> class A(object):
    pass

>>> a.__dict__
{}
>>> vars(a)
{}
>>> a.name = &#39;Kim&#39;
>>> a.__dict__
{&#39;name&#39;: &#39;Kim&#39;}
>>> vars(a)
{&#39;name&#39;: &#39;Kim&#39;}

反射操作

__import__:动态导入模块

index = __import__(&#39;index&#39;)
index.sayHello()

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

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

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

>>> issubclass(bool,int)
True
>>> issubclass(bool,str)
False

>>> issubclass(bool,(str,int))
True

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

#定义类A
>>> class Student:
    def __init__(self,name):
        self.name = name

        
>>> s = Student(&#39;Aim&#39;)
>>> hasattr(s,&#39;name&#39;) #a含有name属性
True
>>> hasattr(s,&#39;age&#39;) #a不含有age属性
False

getattr:获取对象的属性值

#定义类Student
>>> class Student:
    def __init__(self,name):
        self.name = name

>>> getattr(s,&#39;name&#39;) #存在属性name
&#39;Aim&#39;

>>> getattr(s,&#39;age&#39;,6) #不存在属性age,但提供了默认值,返回默认值

>>> getattr(s,&#39;age&#39;) #不存在属性age,未提供默认值,调用报错
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    getattr(s,&#39;age&#39;)
AttributeError: &#39;Stduent&#39; object has no attribute &#39;age&#39;

setattr:设置对象的属性值

>>> class Student:
    def __init__(self,name):
        self.name = name

        
>>> a = Student(&#39;Kim&#39;)
>>> a.name
&#39;Kim&#39;
>>> setattr(a,&#39;name&#39;,&#39;Bob&#39;)
>>> a.name
&#39;Bob&#39;

delattr:删除对象的属性

#定义类A
>>> class A:
    def __init__(self,name):
        self.name = name
    def sayHello(self):
        print(&#39;hello&#39;,self.name)

#测试属性和方法
>>> a.name
&#39;小麦&#39;
>>> a.sayHello()
hello 小麦

#删除属性
>>> delattr(a,&#39;name&#39;)
>>> a.name
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    a.name
AttributeError: &#39;A&#39; object has no attribute &#39;name&#39;

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

>>> class B: #定义类B
    def __call__(self):
        print(&#39;instances are callable now.&#39;)

        
>>> callable(B) #类B是可调用对象
True
>>> b = B() #调用类B
>>> callable(b) #实例b是可调用对象
True
>>> b() #调用实例b成功
instances are callable now.

变量操作

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

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

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

>>> def f():
    print(&#39;before define a &#39;)
    print(locals()) #作用域内无变量
    a = 1
    print(&#39;after define a&#39;)
    print(locals()) #作用域内有一个a变量,值为1

    
>>> f
<function f at 0x03D40588>
>>> f()
before define a 
{} 
after define a
{&#39;a&#39;: 1}

交互操作

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

>>> print(1,2,3)
1 2 3
>>> print(1,2,3,sep = &#39;+&#39;)
1+2+3
>>> print(1,2,3,sep = &#39;+&#39;,end = &#39;=?&#39;)
1+2+3=?

input:读取用户输入值

>>> s = input(&#39;please input your name:&#39;)
please input your name:Ain
>>> s
&#39;Ain&#39;

文件操作

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

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

编译执行

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

>>> #流程语句使用exec
>>> code1 = &#39;for i in range(0,10): print (i)&#39;
>>> compile1 = compile(code1,&#39;&#39;,&#39;exec&#39;)
>>> exec (compile1)
0
1
2
3
4
5
6
7
8
9


>>> #简单求值表达式用eval
>>> code2 = &#39;1 + 2 + 3 + 4&#39;
>>> compile2 = compile(code2,&#39;&#39;,&#39;eval&#39;)
>>> eval(compile2)
10

eval:执行动态表达式求值

>>> eval(&#39;1+2+3+4&#39;)
10

exec:执行动态语句块

>>> exec(&#39;a=1+2&#39;) #执行语句
>>> a
3

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

>>> a = &#39;some text&#39;
>>> str(a)
&#39;some text&#39;
>>> repr(a)
"&#39;some text&#39;"

装饰器

property:标示属性的装饰器

>>> class C:
    def __init__(self):
        self._name = &#39;&#39;
    @property
    def name(self):
        """i&#39;m the &#39;name&#39; property."""
        return self._name
    @name.setter
    def name(self,value):
        if value is None:
            raise RuntimeError(&#39;name can not be None&#39;)
        else:
            self._name = value

            
>>> c = C()

>>> c.name # 访问属性
&#39;&#39;
>>> 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(&#39;name can not be None&#39;)
RuntimeError: name can not be None

>>> c.name = &#39;Kim&#39; # 设置属性
>>> c.name # 访问属性
&#39;Kim&#39;

>>> del c.name # 删除属性,不提供deleter则不能删除
Traceback (most recent call last):
  File "<pyshell#87>", line 1, in <module>
    del c.name
AttributeError: can&#39;t delete attribute
>>> c.name
&#39;Kim&#39;

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

>>> class C:
    @classmethod
    def f(cls,arg1):
        print(cls)
        print(arg1)

        
>>> C.f(&#39;类对象调用类方法&#39;)
<class &#39;__main__.C&#39;>
类对象调用类方法

>>> c = C()
>>> c.f(&#39;类实例对象调用类方法&#39;)
<class &#39;__main__.C&#39;>
类实例对象调用类方法

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

# 使用装饰器定义静态方法
>>> class Student(object):
    def __init__(self,name):
        self.name = name
    @staticmethod
    def sayHello(lang):
        print(lang)
        if lang == &#39;en&#39;:
            print(&#39;Welcome!&#39;)
        else:
            print(&#39;你好!&#39;)

            
>>> Student.sayHello(&#39;en&#39;) #类调用,&#39;en&#39;传给了lang参数
en
Welcome!

>>> b = Student(&#39;Kim&#39;)
>>> b.sayHello(&#39;zh&#39;)  #类实例对象调用,&#39;zh&#39;传给了lang参数
zh
你好

更多编程相关知识,请访问:编程视频!!

以上就是python内置函数有哪些的详细内容,更多请关注https://www.sxiaw.com/其它相关文章!