Python3内置函数大全,文章有点长请耐心一点哦

1.abs()函数

'''
abs() 函数返回数字的绝对值。
绝对值:absolute
正如字面上的意思,可以返回一个绝对值
'''
import math
print('abs(45)的值:',abs(45))
print('abs(-45)的值:',abs(-45))
print('abs(45+23)的值:',abs(45+23))
print('abs(math.pi)的值:',abs(math.pi))

print(help(abs))
'''
运行结果:
abs(45)的值: 45
abs(-45)的值: 45
abs(45+23)的值: 68
abs(math.pi)的值: 3.141592653589793
Help on built-in function abs in module builtins:

abs(x, /)
    Return the absolute value of the argument.

None

在python2 里还可以输出 print "abs(119L) : ", abs(119L)  不过python3中abs函数只能输入int型 不然会报错
'''

2.all()函数详解

'''
all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。
元素除了是 0、空、FALSE 外都算 TRUE。
语法
以下是 all() 方法的语法:
all(iterable)
参数
iterable -- 元组或列表。
返回值
如果iterable的所有元素不为0、''、False或者iterable为空,all(iterable)返回True,否则返回False;
注意:空元组、空列表返回值为True,这里要特别注意。
'''
print(all(['a','b','c','']))   #列表存在一个为空的元素,返回False
print(all(['a','b','c','d']))  #列表都有元素,返回True
print(all([0,1,2,3,4,5,6]))    #列表里存在为0的元素 返回False

print(all(('a','b','c','')))   #元组存在一个为空的元素,返回Fasle
print(all(('a','b','c','d')))  #元组都有元素,返回True
print(all((0,1,2,3,4,5)))      #元组存在一个为0的元素,返回Fasle

print(all([]))  #空列表返回 True
print(all(()))  #空元组返回 True

3.any()函数

'''
any() 函数用于判断给定的可迭代参数 iterable 是否全部为 False,则返回 False,如果有一个为 True,则返回 True。
元素除了是 0、空、FALSE 外都算 TRUE。
语法
以下是 any() 方法的语法:
any(iterable)
参数
iterable -- 元组或列表。
返回值
如果都为空、0、false,则返回false,如果不都为空、0、false,则返回true。
'''
print(any(['a','b','c','']))   #列表存在一个为空的元素,返回True
print(any(['a','b','c','d']))  #列表都不为空,返回True
print(any([0,'',False]))       #列表里的元素全为  0,'',False  返回False

print(any(('a','b','c','')))   #元组存在一个为空的元素,返回True
print(any(('a','b','c','d')))  #元组都有元素,返回True
print(any((0,'',False)))       #元组里的元素全为  0,'',False  返回False

print(any([]))  #空列表返回 False
print(any(()))  #空元组返回 False

4.ascii()函数

'''
ascii() 函数类似 repr() 函数, 返回一个表示对象的字符串,
但是对于字符串中的非 ASCII 字符则返回通过 repr() 函数使用 \x, \u 或 \U 编码的字符。
生成字符串类似 Python2 版本中 repr() 函数的返回值。
语法
以下是 ascii() 方法的语法:
ascii(object)

参数
object -- 对象。

返回值
返回字符串
'''
print(ascii('uiatfu'))

#报错 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 427-428: truncated \xXX escape
#不知道为何

5.bin()函数

'''
函数原型
bin(x)
参数解释
x
整数型,参数不可为空。
返回值
<class 'str'> 字符串类型,二进制整数。
函数说明
将一个整数转化为一个二进制整数,并以字符串的类型返回。
---------------------------------------------------------------------
学Python的过程中,往往因为没有资料或者没人指导从而导致自己不想学下去, 因此特意准备了个QQ群991032883,可以获取源码,解答,学习路线、开发工具等给大家免费使用! 
'''
print(bin(12))          #输出12的二进制 0b1100
print(bin(-120))        #输出-12的二进制 -0b1111000
print(type(bin(12)))    #输出bin(12) 的类型 <class 'str'> 所以不能直接计算

print(int(bin(10),base=2)+int(bin(20),base=2))  #输出 30

#base 参数不可为空 为空默认参数为10进制 会报错 ValueError: invalid literal for int() with base 10: '0b1010'

#当然了,参数不仅可以接受十进制整数,八进制、十六进制也是可以的,只要是int型数据就合法。

print(bin(0b10010))    #输出0b10010
print(bin(0o1357))     #输出0b1011101111
print(bin(0x2d9))      #输出0b1011011001

6.bool()函数

'''
描述
bool() 函数用于将给定参数转换为布尔类型,如果没有参数,返回 False。
bool 是 int 的子类。
语法
以下是 bool() 方法的语法:
class bool([x])
参数
x -- 要进行转换的参数。
返回值
返回 Ture 或 False。
'''
print(bool(0))         #返回False
print(bool(1))         #返回True
print(bool(True))      #返回True
print(bool(False))     #返回False
print(bool(''))        #返回False


#0,False,'',  空字符串返回Fasle

7.bytes()函数

'''
描述
bytes 函数返回一个新的 bytes 对象,该对象是一个 0 <= x < 256 区间内的整数不可变序列。
它是 bytearray 的不可变版本。

语法
以下是 bytes 的语法:
class bytes([source[, encoding[, errors]]])
参数
如果 source 为整数,则返回一个长度为 source 的初始化数组;
如果 source 为字符串,则按照指定的 encoding 将字符串转换为字节序列;
如果 source 为可迭代类型,则元素必须为[0 ,255] 中的整数;
如果 source 为与 buffer 接口一致的对象,则此对象也可以被用于初始化 bytearray。
如果没有输入任何参数,默认就是初始化数组为0个元素。
返回值
返回一个新的 bytes 对象。

将一个字符串转换成字节类型
'''
print(bytes('python',encoding='utf-8'))   #输出b'python'
print(bytes('张三',encoding='utf-8'))     #输出b'\xe5\xbc\xa0\xe4\xb8\x89'

print(bytes([1,2,3,4]))                   #输出b'\x01\x02\x03\x04'
print(bytes('hello','ascii'))             #输出b'hello'
print(type(bytes([1,2,3])))               #输出<class 'bytes'>

8.challable()函数

'''
challable()  判断对象是否可以被调用,
能被调用的对象就是一个callables对象,
比如函数和带有__call__()的实例
'''

print(callable(max))       #输出True
print(callable([1,2,3]))   #输出Fasle
print(callable(None))      #输出Fasle
print(callable('str'))     #输出Fasle


def fn(x):
    return x*x
print(callable(fn))        #输出True  证明自定义的函数也可以

9.chr()函数

'''
查看十进制数对应的ASCII码值
描述
chr() 用一个整数作参数,返回一个对应的字符。
语法
以下是 chr() 方法的语法:
chr(i)
参数
i -- 可以是 10 进制也可以是 16 进制的形式的数字,数字范围为 0 到 1,114,111 (16 进制为0x10FFFF)。
返回值
返回值是当前整数对应的 ASCII 字符。
'''

#print(chr(-1))   #报错 ValueError: chr() arg not in range(0x110000) 超出范围 不能小于0

print(chr(0x30))     #输出 0
print(chr(97))       #输出 a
print(chr(8364))     #输出 €

10.classmethod()函数

'''
描述
classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,
但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。
语法
classmethod 语法:
classmethod
参数
无。
返回值
返回函数的类方法。
---------------------------------------------------------------------
学Python的过程中,往往因为没有资料或者没人指导从而导致自己不想学下去, 因此特意准备了个QQ群991032883,可以获取源码,解答,学习路线、开发工具等给大家免费使用! 
'''

class Stud:
    num=1
    def fn1(self):
        print('方法一')
    @classmethod
    def fn2(cls):
        print('方法二')   #输出 方法二
        print(cls.num)    #调用类的实例化对象
        cls().fn1()       #调用类的方法

Stud.fn2()    #输出 方法二 不需要实例化

print('===='*10)
object=Stud()
object.fn1()  #输出 方法一 需要实例化

11.complex()函数

'''
描述
complex() 函数用于创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。
如果第一个参数为字符串,则不需要指定第二个参数。。
语法
complex 语法:
class complex([real[, imag]])
参数说明:
real -- int, long, float或字符串;
imag -- int, long, float;
返回值
返回一个复数。
'''

print(complex(1,2))          #输出  (1+2j)
print(complex(1))            #输出  (1+0j)
print(complex('2'))          #输出  (2+0j)

# 注意:这个地方在"+"号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错
print(complex('2+3j'))       #输出  (2+3j)

print(complex(1.2,3.4))      #输出  (1.2+3.4j)

12.complie()函数

'''
complie()  将字符串编译成python能识别或可以执行的代码,也可以将文字读成字符串再编译

1 compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
2 将source编译为代码或者AST对象。代码对象能过通过exec语句来执行或者eval()进行求值。
3 参数source:字符串或者AST(abstract syntax trees)对象。
4 参数filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。
5 参数model:指定编译代码的种类。可以指定'exec', 'eval', 'single'。
6 参数flag和dont_inherit:这两个参数为可选参数。
'''

s="print('hello world')"
r=compile(s,'hello','exec')
print(r)

#输出结果:
#<code object <module> at 0x000002EBD335CF60, file "hello", line 1>

13.delattr()函数

'''
描述:
delattr函数用于删除属性
delattr(x,'foobar)相当于del x.foobar
语法:
setattr(object,name)
参数:
object--对象
name--必须是对象的属性
返回值:
无
'''

class People():
    sex='男'
    def __init__(self,name):
        self.name=name
    def peopleinfo(self):
        print('欢迎%s访问'%self.name)

delattr(People,'sex')  #等同于 del People.sex
print(People.__dict__)

#输出 {'__module__': '__main__', '__init__': <function People.__init__ at 0x000001CE3E2E52F0>, 'peopleinfo': <function People.peopleinfo at 0x000001CE3E2E5378>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None}

class Foo:
    def run(self):
        while True:
            cmd=input('cmd>>: ').strip()
            if hasattr(self,cmd):
                func=getattr(self,cmd)
                func()
    def download(self):
        print('download....')
    def upload(self):
        print('upload...')
obj=Foo()
obj.run()

14.dict()函数

'''
描述
dict() 函数用于创建一个字典。
语法
dict 语法:
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
参数说明:
**kwargs -- 关键字
mapping -- 元素的容器。
iterable -- 可迭代对象。
返回值
返回一个字典。
---------------------------------------------------------------------
学Python的过程中,往往因为没有资料或者没人指导从而导致自己不想学下去, 因此特意准备了个QQ群991032883,可以获取源码,解答,学习路线、开发工具等给大家免费使用! 
'''

print(dict())   #创建空字典
dict1=dict(a='a', b='b', t='t')   #传入关键字 构建字典
print(dict1)    #输出 {'a': 'a', 'b': 'b', 't': 't'}

dict2=dict(zip(['one', 'two', 'three'], [1, 2, 3]))   # 映射函数方式来构造字典
print(dict2)    #输出 {'one': 1, 'two': 2, 'three': 3}

dict3=dict([('one', 1), ('two', 2), ('three', 3)])    # 可迭代对象方式来构造字典
print(dict3)     #输出 {'one': 1, 'two': 2, 'three': 3}

15.dir()函数

'''
dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。
语法
dir 语法:
dir([object])
参数说明:
object -- 对象、变量、类型。
返回值
返回模块的属性列表。
'''

print(dir())        #获得当前模块的属性列表
#输出 ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
print(dir([]))      #获得列表的方法
#输出 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__
print(dir(str))     #获得字符串的方法
#输出 ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
print(dir(dict))    #获得字典的方法
#输出 ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

def update_func(var):
    print("var 的内存地址:", id(var))
    var += [4]

lst_1 = [1, 2, 3]

print(dir())  #输出 ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'lst_1', 'update_func']

class Shape:
    def __dir__(self):
        return ['area', 'perimeter', 'location']

s = Shape()
print(dir(s))   #输出 ['area', 'location', 'perimeter']

16.divmod()函数

'''
python divmod() 函数把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)。
在 python 2.3 版本之前不允许处理复数。
函数语法
divmod(a, b)
参数说明:
a: 数字
b: 数字
---------------------------------------------------------------------
学Python的过程中,往往因为没有资料或者没人指导从而导致自己不想学下去, 因此特意准备了个QQ群991032883,可以获取源码,解答,学习路线、开发工具等给大家免费使用! 
'''
print(divmod(20,4))   #返回  (5, 0)
print(divmod(7,2))    #返回  (3, 1)
print(divmod(8,2))    #返回  (4, 0)
#print(divmod(1+2j,1+0.5j))
#报错 TypeError: can't take floor or mod of complex number.

17.enumerate()函数

'''
enumerate是翻译过来是枚举的意思,看下它的方法原型:
enumerate(sequence, start=0),返回一个枚举对象。
sequence必须是序列或迭代器iterator,或者支持迭代的对象。
enumerate()返回对象的每个元素都是一个元组,
每个元组包括两个值,一个是计数,一个是sequence的值,
计数是从start开始的,start默认为0。
---------------------
'''
a=["q","w","e","r"]
c
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值