python进阶--内置函数

abs(): 返回该数值的绝对值:

>>> a = -1
>>> abs(a)
1
>>> a = 1
>>> abs(a)
1

all():查看一个可迭代对象中是否有为假,返回:True/False。

>>> all([1,2,3,4,5])
True
>>> all([1,2,3,'',4,5])
False
>>> all({"12":""})
True
>>> all({"":""})
False
>>> all((1,2,3,4,"",))
False
>>> all(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> all([0,0,0,0])
False

any():同all(),不同的是,当这个可迭代对象中全部为假返回False,否则True

>>> any([1,2,3,4,5,0,0,0,'',False])
True
>>> any([0,'',False,[],{},()])
False

ascii():这个函数跟repr()函数一样,返回一个可打印的对象字符串方式表示。当遇到非ASCII码时,就会输出\x,\u或\U等字符来表示:

>>> ascii(1)
'1'
>>> ascii('as')
"'as'"
>>> ascii('gh')
"'gh'"
>>> ascii(b'gh')
"b'gh'"
>>> ascii('b\31')
"'b\\x19'"

bin():将int类型的对象转换成二进制表现形式

>>> bin(3)
'0b11'
>>> bin(4)
'0b100'
>>> bin(5)
'0b101'

bool():查看被传入的对象是否为真,返回True/False.

>>> bool(1)
True
>>> bool(0)
False
>>> bool('')
False
>>> bool('1')
True

bytearray():返回字节序列

>>> bytearray(8)
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')
>>> bytearray('aa')
bytearray(b'aa')
>>> bytearray('bb')
bytearray(b'bb')
>>> bytearray(b'bb')
bytearray(b'bb')
>>> bytearray('哈哈','utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)
>>> bytearray(u'哈哈','utf-8')
bytearray(b'\xe5\x93\x88\xe5\x93\x88')

bytes():返回字节序列,如果是整数,会返回字符串。

>>> bytes('bb')
'bb'
>>> bytes(u'bb')
'bb'
>>> bytes(1)
'1'

calable():查看对象是否有返回

>>> callable(1)
False
>>> callable(0)
False
>>> def a(x):
...     return x
... 
>>> callable(a)
True

chr():查看十进制数值在二进制中表示那个数值

>>> chr(65)
'A'
>>> chr(78)
'N'
>>> chr(90)
'Z'

classmethod():装饰器,指定一个类的方法为类方法,没有这个参数的类方法则是实例方法

>>> class A:
...     @classmethod
...     def a(cls):
...         print('这是一个类方法,而不是实例方法,但是也可以用实例方法来调用')
... 
>>> A.a()
这是一个类方法,而不是实例方法,但是也可以用实例方法来调用
>>> A().a()
这是一个类方法,而不是实例方法,但是也可以用实例方法来调用

compile(source, filename, mode[, flags[, dont_inherit]])):source要运行的代码,filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值,

>>> compile('for i in range(10): print(i)', '', 'exec')
<code object <module> at 0x10652fa30, file "", line 1>
>>> a = compile('for i in range(10): print(i)', '', 'exec')
>>> exec(a)
0
1
2
3
4
5
6
7
8
9

delattr(object, str):第一个参数是一个对象,第二个参数是一个字符串,作用是删除object中str属性

>>> class A:
...     def __init__(self):
...             self.l = '1'
...             self.k = 'k'
... 
>>> a = A()
>>> a.l
'1'
>>> delattr(a, 'l')
>>> a.l
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'l'
# 如果对象中没有str这个属性会报AttributeError

dir():如果没有参数就会返回当前作用的所有名字列表,如果有参数,则返回这个参数所拥有的方法

>>> dir()
['A', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a']
>>> dir(a)
['__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__', 'k']

file():使用方法如同open()会打开文件,构建一个文件对象。但是建议使用open()来操作文件,file(),可以用来检测对象类型:

>>> isinstance(a, file)

filter(function, iterable)
构造一个列表,列表的元素来自于iterable,对于这些元素function返回真。iterable可以是个序列,支持迭代的容器,或者一个迭代器。如果iterable是个字符串或者元组,则结果也是字符串或者元组;否则结果总是列表。如果function是None,使用特性函数,即为假的iterable被移除。返回结果是一个生成器。python3.6

>>> def a(x):
...     return x
>>> filter(a, [i for i in range(10)])
<filter object at 0x102198fd0>

getattr(obj, str):如同delattr()函数一样的参数,不过是返回这个对象中str属性值,如果没有该属性会抛出一个异常

>>> class A:
...     def __init__(self):
...             self.l = '1'
...             self.k = '2'
... 
>>> a = A()
>>> a.l
'1'
>>> a.k
'2'
>>> getattr(a, 'l')
'1'
>>> getattr(a, '1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute '1'

globals():返回当前环境下的所有全局属性,字典

>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'A': <class '__main__.A'>, 'a': <__main__.A object at 0x1021a10b8>, 'c': 3}

hasattr(obj, str):返回obj对象中是否有str属性,如果有返回True,否则返回False

>>> hasattr(a,'l')
True

hash():返回参数中对象的散列值,如果该对象没有散列值则抛出一个异常

>>> hash(a)
-9223372036584136437
>>> a = [1,2,3,1]
>>> hash(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

hex():将一个整数转换成16进制

>>> hex(1)
'0x1'
>>> hex(2)
'0x2'

isinstance(obj, classinfo):检测obj是否是classinfo类型或者实例

>>> class A():
...     def __init__(self):
...             pass
... 
>>> a = A()
>>>> isinstance(a, A)
True
>>> type(a)
<class '__main__.A'>
>>> isinstance(1, int)
True

issubclass(obj,obj1):检查obj是否是obj的子类

>>> class A():
...     def __init__(self):
...             pass
... 
>>> class s(A):
...     def __init__(self):
...             pass
>>> issubclass(s, A)
True

map():同filter()
max():在一个可迭代的对象中寻找最大的元素

>>> max([1,2,3,4,5,6,7,8,9])
9
>>> max(["123","345","986","1"])
'986'
>>> max(["123","345","0001","1"])
'345'
>>> max(["123","345","asdf","1"])
'asdf'

min():同max(), 不同的是返回最小的元素
next(obj):obj必须时一个生成器对象,返回该对象下一个值

>>> def a():
...     for i in range(10):
...             yield i
>>> next(a())
0

object():返回一个无特征的新对象

>>> a = object()
>>> a
<object object at 0x100639110>

oct():将整数转成八进制

>>> oct(1)
'0o1'
>>> oct(3)
'0o3'

open(filename, str):打开一个文件,fielname文件的路径,str按照什么方式来打开

>>> f = open('1.txt', 'wb')
>>> type(f)
<class '_io.BufferedWriter'>
>>> f
<_io.BufferedWriter name='1.txt'>

未完待续

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值