简介
python内置了一系列的常用函数,以便于我们使用,python英文官方文档详细说明:点击查看。
反射类操作
callable()
用于检查一个对象是否是可调用的。如果返回 True,object 仍然可能调用失败;但如果返回 False,调用对象 object 绝对不会成功。
注意!对于函数、方法、lambda 函式、 类以及实现了 _ _ call _ _ 方法的类实例, 它都返回 True。
>>> def add(a, b):... return a + b... >>> callable(add) # 函数返回 TrueTrue>>> class B:... def __call__(self):... return 0... >>> callable(B)True
classmethod()
对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。
class A(object):bar = 1def func1(self): print ('foo') @classmethoddef func2(cls):print ('func2')print (cls.bar)cls().func1() # 调用 foo 方法A.func2() # 不需要实例化
staticmethod()
返回函数的静态方法。该方法不强制要求传递参数
class main:#先声明类def set(self, x): #普通方法print(x)@staticmethod #类方法def run(n):print(n)o = main() #普通方法需要实例化后才能调用o.set('abc')#输出abcmain.run(123) #类方法可以直接使用,不需要实例化#输出123
compile()
将字符串代码或者代码文件解析转化为可执行代码或AST对象,根据代码的内容和类型分别由exec()、eval()两个函数进行执行。
注意!
1.当source包含一些列语句(例如for循环语句)应当使用exec模式
2.当source为单个表达式组成应当使用eval模式
3.当source由单个交互式语句组成(例如input)则应当使用single模式。
#实例一:
l = "for i in ['aaaaa', 'bbbbb', 'ccccc', 'ddddd', 'eeeee']: print(i)"
c = compile(l, '', 'exec')
exec(c)
#结果
aaaaa
bbbbb
ccccc
ddddd
eeeee#实例二:
s = "print(30 + 5 - 10)"
c = compile(s,'','eval')
eval(c)
#结果
25#实例三:
p = 'input("请输入你的生日:")'
c = compile(p, '', 'single')
exec(c)
#结果
请输入你的生日2010-10-10
'2010-10-10'
dir
获取当前本地名称列表
>>> dir()['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
获取模块属性列表
>>> import sys>>> dir(sys)['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache',。。。。(此处省略一万字)
获取类的有效属性列表
>>> class main:... a = 1... b = 2... c = 3... def run(self):... print(123)>>> o = main()>>> dir(o)['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'c', 'run']
获取dir()设置的属性列表
>>> class main:... a = 1... b = 2... c = 3... def run(self):... print(123)... def __dir__(self):... return ['d', 'e', 'f']>>> o = main()>>> dir(o)['d', 'e', 'f']
eval()
用来执行一个字符串表达式,并返回表达式的值
>>>x = 7>>> eval( '3 * x' )21>>> eval('pow(2,2)')4>>> eval('2 + 2')4
exec()
执行储存在字符串或文件中的 Python 语句,相比于 eval,exec可以执行更复杂的 Python 代码
>>>exec('print("Hello World")')Hello World# 单行语句字符串>>> exec("print ('runoob.com')")runoob.com# 多行语句字符串>>> exec ("""for i in range(5):... print ("iter time: %d" % i)... """)iter time: 0iter time: 1iter time: 2iter time: 3iter time: 4
filter()
用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象
def odd(n):return n % 2 == 1tmp = filter(odd,range(1,20))print(list(tmp))#结果[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
getattr()
返回一个对象属性值,如果没有,可以设置
>>> class A(object):bar = 1a = A()>>> print(getattr(a,'bar')) #获取属性bar的值1>>> print(getattr(a,'bar2')) #属性bar2不存在,触发异常Traceback (most recent call last):File "<stdin>", line 1, in <module>AttributeError: 'A' object has no attribute 'bar2'>>> print(getattr(a,'bar2',3)) #属性bar2不存在,但设置了默认值。3
setatt()
对应函数 getattr(),用于设置属性值,该属性不一定是存在的。
>>>class A(object):... bar = 1... >>> a = A()>>> getattr(a, 'bar') # 获取属性 bar 值1>>> setattr(a, 'bar', 5) # 设置属性 bar 值>>> a.bar5
globals()
会以字典类型返回当前位置的全部全局变量。
>>> print(globals()){'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 'baidu'}
hasattr()
用于判断对象是否包含对应的属性。
class Coordinate:x = 10y = -5z = 0point1 = Coordinate() print(hasattr(point1, 'x'))print(hasattr(point1, 'y'))print(hasattr(point1, 'z'))print(hasattr(point1, 'no')) # 没有该属性#结果TrueTrueTrueFalse
hash()
用于获取取一个对象(字符串或者数值等)的哈希值。
可以应用于数字、字符串和对象,不能直接应用于 list、set、dictionary。
函数的对象字符不管有多长,返回的 hash 值都是固定长度的,也用于校验程序在传输过程中是否被第三方(木马)修改。
hash('test')
456767774483869837
hash(1)
1
hash(str([1,2,3,4,5]))
593718760398909611
id()
返回对象的内存地址
>>> a = 1>>> id(a)8791233520464
isinstance()
来判断一个对象是否是一个已知的类型
>>> id(a)8791233520464>>> a = 2>>> isinstance(a,str)False>>> isinstance(a,int)True
type()
如果只有第一个参数则返回对象的类型,三个参数返回新的类型对象。
#一个参数>>> type(1)<type 'int'>>>> type('baidu')<type 'str'>#三个参数>>> class X(object):a = 1>>> X = type('X',(object,),dict(a=1))>>> X<class '__main__.X'>
issubclass()
用于判断参数 class 是否是类型参数 classinfo 的子类。
>>> class A:pass>>> class B(A):pass>>> print(issubclass(B,A))True
len()
返回对象(字符、列表、元组等)长度或项目个数。
>>>str = "runoob">>> len(str) # 字符串长度6>>> l = [1,2,3,4,5]>>> len(l) # 列表元素个数5
local()
会以字典类型返回当前位置的全部局部变量。
#实例一:>>>def runoob(arg): # 两个局部变量:arg、z... z = 1... print (locals())... >>> runoob(4){'z': 1, 'arg': 4} # 返回一个名字/值对的字典#实例二:>>> out = 1 #声明全局变量out。>>> def run(inside): #声明方法,方法有一个inside参数。... print(locals())...>>> run(5) #运行方法#结果{'inside':5}#实例三:class A(object):#声明类bar = 1def run(self):print(locals())app = A()#实例化类app.run()#运行类中的方法run#结果{'self': <__main__.A object at 0x0000000002517CC0>}
map()
会根据提供的函数对指定序列做映射。
def fun(x):return x ** 2print(list(map(fun, [1,2,3,4,5])))#结果[1, 4, 9, 16, 25]
memoryview()
返回给定参数的内存查看对象(Momory view)。
>>>v = memoryview(bytearray("abcefg", 'utf-8'))>>> print(v[1])98>>> print(v[-1])103>>> print(v[1:4])<memory at 0x10f543a08>>>> print(v[1:4].tobytes())b'bce'
next()
返回迭代器的下一个项目。
a = iter([1,2,3,4,5])while 1: #循环try:x = next(a) #获得下一个值print(x)except StopIteration:break #遇到异常退出循环#结果12345
property()
主要作用是设置类属性的方法,用于指定属性的获取、修改和删除的对应方法,可以增加对属性的限制,例如验证、过滤、二次处理等。
class User():def __init__(self):self._age = 0def getAge(self):print('正在获取年龄')return self._agedef setAge(self,value):print('正在设置年龄')self._age = valuedef delAge(self):print('正在删除年龄属性')del self._ageage = property(getAge,setAge,delAge,'这是设置年龄的属性')u = User()>>> u.age = 18#结果正在设置年龄属性>>> u.age#结果正在获取年龄属性del u.age#结果正在删除年龄属性>>> help(User.age)Help on property:这是设置年龄的property属性
需要注意的是,虽然我们将getAge,setAge,delAge这三个方法设置给了age属性,但是它们同时也属于类本身,实例化后可以直接被调用,换句话说,这三个方法也暴露给了外部,在一些特定的情况下可能会造成一些混乱,这可能不会是严重的问题。
repr()
将对象转化为供解释器读取的形式。
>>>s = 'RUNOOB'>>> repr(s)"'RUNOOB'">>> dict = {'runoob': 'runoob.com', 'google': 'google.com'};>>> repr(dict)"{'google': 'google.com', 'runoob': 'runoob.com'}">>>
slice()
实现切片对象,主要用在切片操作函数里的参数传递。
>>> s = slice(5,7)>>> l = [1,2,3,4,5,6,7,8,9,10]>>> l[s][6, 7]
super()
用于调用父类(超类)的一个方法。
class A:def add(self, x):y = x+1print(y)class B(A):def add(self, x):super().add(x)b = B()b.add(2) # 3
vars()
返回对象object的属性和属性值的字典对象。
>>> class X(object):a = 1>>> print(vars(X)){'a': 1, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'X' objects>, '__weakref__': <attribute '__weakref__' of 'X' objects>, '__doc__': None}
bytearray()
返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。
>>> bytearray()bytearray(b'')>>> bytearray([1,2,3])bytearray(b'\x01\x02\x03')>>> bytearray('baidu','utf-8')bytearray(b'baidu')