首页 > 其他分享 >10.内置函数

10.内置函数

时间:2022-11-03 14:33:56浏览次数:74  
标签:__ 10 内置 函数 返回 object print 100 iterable

截止到python3.9,一共有60多个内置函数,本篇对常用的函数进行分类罗列一下,对于文档请查看

https://docs.python.org/zh-cn/3.9/library/functions.html

1.数学运算

  1. abs(x):返回一个数的绝对值
    print(abs(-100))  # 100
  2. max(iterable):返回一个可迭代序列的最大值
    print(max([1, 2, 3, 4, 6, 100, 100]))  # 100
  3. min(iterable):返回一个可迭代序列的最小值
    print(min([1, 2, 3, 4, 6, 100, 100]))  # 1
  4. round(number[, ndigits]):返回 number 舍入到小数点后 ndigits 位精度的值。 如果 ndigits 被省略或为 None,则返回最接近输入值的整数。
    print(round(2.475, 1)) # 2.5
    print(round(3.141))  # 3
  5. sum(iterable, /, start=0):在start的基础上 开始自左向右对 iterable 的项求和并返回总计值。 iterable 的项通常为数字,而 start 值则不允许为字符串。
    var = [1, 2, 3, 4, 5]
    print(sum(var))  # 15
    print(sum(var, start=2))  # 17
  6. divmod(a,b):返回a/b的商和余数
    print(divmod(5,3))  # (1, 2)
  7. pow(base, exp):返回 baseexp 次幂
    print(pow(10,3))  # 1000

2.类型转化

  1. bool(x):根据参数x返回True或者False
    print(bool(0))  # False
    print(bool(1))  # True
  2. int(x, base=10):根据base进制将x转换为十进制,返回一个正整数
    print(int(10.2))  # 10
    print(int('10'))  # 10
    print(int('0b001010', base=2))  # 10
  3. float(x):返回从数字或者字符串x生成的浮点数
    print(float(10))  # 10.0
    print(float('10'))  # 10.0
  4. complex(x):转换为复数
    print(complex(1, 2))  # (1+2j)
    print(complex('1+2j'))  # (1+2j)
  5. str(x):返回一个str版本的object
    print(str(1))  # 1
    print(str([1, 2, 3]))  # [1, 2, 3]
    print(str(True))  # True
  6. bytearray(source,encoding):返回一个bytes数组
    print(bytearray('中国心', 'utf-8'))  #bytearray(b'\xe4\xb8\xad\xe5\x9b\xbd\xe5\xbf\x83')
  7. bytes(source,encoding):返回一个新的“bytes”对象, 是一个不可变序列
    print(bytes('中国心', 'utf-8'))  #b'\xe4\xb8\xad\xe5\x9b\xbd\xe5\xbf\x83'
  8. ord(c):对表示单个 Unicode 字符的字符串,返回代表它 Unicode 码点的整数
    print(ord('赵'))  # 36213
    print(ord('A'))  # 65
  9. chr(i):返回 Unicode 码位为整数 i 的字符的字符串格式
    print(chr(36213))  # 赵
  10. bin(x):将一个整数转换为一个前缀为“0b”二进制形式的字符串
    print(bin(10))  # 0b1010
  11. oct(x):将一个整数转变为一个前缀为“0o”的八进制字符串
    print(oct(10))  # 0o12
  12. hex(x):将整数转换为以“0x”为前缀的小写十六进制字符串
    print(hex(10))  # 0xa
  13. tuple(iterable):将序列转变为一个不可变的元组序列
    print(tuple([1,2,3]))  # (1, 2, 3)
  14. list(iterable):将序列转变为一个可变的列表序列
    print(list((1,2,3)))  # [1, 2, 3]
  15. dict(**kwargs)/dict(mapping,**kwargs)/dict(iterable,**kwargs):创建一个新的字典set
    print(dict(name='kunmzhao', age=18))  # {'name': 'kunmzhao', 'age': 18}
    print(dict(zip(['name', 'age'], ['kunmzhao', 18])))  # {'name': 'kunmzhao', 'age': 18}
    print(dict([('name', 'kunmzhao'), ('age',18)]))  # {'name': 'kunmzhao', 'age': 18}
  16. set(iterable):返回一个新的 set 对象
  17. range(start, end, step):表示不可变的数字序列,通常用于在for环中循环指定的次数。
    print(list(range(1, 11)))  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    for i in range(3):
        print('hello')
  18. iter(object):返回一个 iterator 对象
    print(iter([1, 2, 3]))  # <list_iterator object at 0x000001ECC45F4760>
  19. super():返回一个代理对象,它会将方法调用委托给 type 的父类或兄弟类
  20. enumerate(iterablestart=0)):返回一个枚举对象。iterable 必须是一个序列
    print(list(enumerate(['apple', 'pear', 'banana'])))  #[(0, 'apple'), (1, 'pear'), (2, 'banana')]
    for index, ele in enumerate(['apple', 'pear', 'banana'], start=1):
        print(index, ele)
           
    """
    1 apple
    2 pear
    3 banana
    """
  21. object:返回一个没有特征的新对象。object 是所有类的基类。它具有所有 Python 类实例的通用方法

3.序列操作

  1. all(iterable):如果 iterable 的所有元素均为真值(或可迭代对象为空)则返回 True
    print(all([1, 2, 3, 4,0]))  # False
  2. any(iterable):如果 iterable 的任一元素为真值则返回 True
    print(any((None, '', False, '0')))  # True
  3. filter(function, iterable):用 iterable 中函数 function 返回真的那些元素,构建一个新的迭代器
    print(list(filter(lambda x:x%2==0, range(0,20))))  # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
  4. map(functioniterable):返回一个将 function 应用于 iterable 中每一项并输出其结果的迭代器
    print(list(map(lambda x:x+1, [1, 4, 5])))  # [2, 5, 6]
  5. next(iterator[, default]):通过调用 iterator 的 __next__() 方法获取下一个元素。如果迭代器耗尽,则返回给定的 default,如果没有默认值则触发 StopIteration
    it = iter('hello world')
    print(next(it))  # h
  6. reversed(seq):返回一个反向的 iterator。 seq 必须是一个具有 __reversed__() 方法
    print(list(reversed([1, 2, 3])))  # [3, 2, 1]
    print(''.join(list(reversed('hello world'))))  #dlrow olleh
  7. sorted(iterablekey=Nonereverse=False):根据 iterable 中的项返回一个新的已排序列表。
    print(sorted([1, 2, 9, 5,2,0]))  #[0, 1, 2, 2, 5, 9]
    
    var_dict = {1:1, 9:9,8:8,2:2}
    print(sorted(var_dict.items(), key=lambda x:x[0]))  #[(1, 1), (2, 2), (8, 8), (9, 9)]
  8. zip(*iterables):创建一个聚合了来自每个可迭代对象中的元素的迭代器。
    print(list(zip((0, 1, 2),('name', 'age', 'gender'),('kunmzhao', 18, 'man'))))  # [(0, 'name', 'kunmzhao'), (1, 'age', 18), (2, 'gender', 'man')]

4.对象操作

  1. help(object):启动内置的帮助系统(此函数主要在交互式中使用)
  2. dir(object):返回该对象的有效属性列表
    通过该方法可以很好地了解对象含有的所有属性和方法
    num = 10
    print(dir(num)) #['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
    var = 'hello'
    print(dir(var))  #['__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', 'isascii', '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']
  3. id(object):返回对象的“标识值”,也就时内存空间地址,是一个整数
    num = 10
    var = 'hello'
    print(id(num), id(var))  # 140709121300528 1967175830640
  4. hash(object):返回该对象的哈希值(如果它有的话)。哈希值是整数。它们在字典查找元素时用来快速比较字典的键
    print(hash(100))  # 100
    print(hash(100.0))  # 100.0
    print(hash('100'))  # 6312876305134639668
  5. type(object):返回对象的object类型
    print(type(100))  # <class 'int'>
    print(type([1,2 ,3]))  # <class 'list'>
  6. len(s):返回对象的长度(元素个数)
    print(len('kunmzhao'))  # 8
    print(len([1, 2, 3]))  # 3

5.反射操作

  1. getattr(obj, name, default):返回对象命名属性的值。name 必须是字符串。如果该字符串是对象的属性之一,则返回该属性的值。例如, getattr(x, 'foobar') 等同于 x.foobar。如果指定的属性不存在,且提供了 default 值,则返回它
    class foobar():
        x = 100
    
    
    print(getattr(foobar, 'x', '188'))  # 100
  2. setattr(obj, name, value): 字符串指定一个现有属性或者新增属性。 函数会将值赋给该属性, 例如,setattr(x, 'foobar', 123) 等价于 x.foobar = 123
    class foobar():
        x = 100
    
    
    setattr(foobar, 'y', '88')
    print(foobar.y)  #88
  3. hasattr(obj, name):该实参是一个对象和一个字符串。如果字符串是对象的属性之一的名称,则返回 True,否则返回 False
    class foobar():
        x = 100
    
    
    print(hasattr(foobar, 'x'))  # True
    print(hasattr(foobar, 'y'))  # False
  4. delattr(obj, name):实参是一个对象和一个字符串。该字符串必须是对象的某个属性。该函数将删除指定的属性。例如 delattr(x, 'foobar') 等价于 del x.foobar 。
    class foobar():
        x = 100
    
    print(hasattr(foobar, 'x'))  # True
    delattr(foobar, 'x')
    print(hasattr(foobar, 'x'))  # False
  5. callable(object):如果参数 object 是可调用的就返回 True,否则返回 False
    def fun():
        pass
    
    print(callable(fun))  # True
    print(callable(100))  # False
  6. issubclass(object, classinfo):判断类object是否是classinfo类的子类,是则返回True,否则为False
    class Foobar(object):
        pass
    
    print(issubclass(Foobar, object))  # True
    print(issubclass(object, Foobar))  # False
  7. isinstance(object, classoinfo):如果参数 object 是参数 classinfo 的实例或者是其 (直接、间接或 虚拟) 子类则返回 True
    class Foobar(object):
        pass
    
    
    print(isinstance(Foobar(), object))

     

6.变量操作

  1. gobals():返回当前作用域内的全局变量和其值组成的字典
    def fun():
        a = 100
        b = 200
        print(locals())  # {'a': 100, 'b': 200}
    fun()
  2. locals():返回当前作用域内的局部变量和其值组成的字典
    在函数可以快速将局部变量全部传递给其它函数 **locals()
    def fun():
        a = 100
        b = 200
        print(globals())  
    # {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001D2B0273DF0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:/Users/kunmzhao/Desktop/victor/review/test.py', '__cached__': None, 'fun': <function fun at 0x000001D2B02BD1F0>}fun()

     

7.装饰器

  1. @property:将方法编程属性调用
    class Foo():
        @property
        def myfun(self):
            print('hello')
    
    Foo().myfun  # hello
  2. @classmethod:把一个方法封装成类方法,一个类方法把类自己作为第一个实参
    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
  3. @staticmethod:将方法转换为静态方法,静态方法不会接收隐式的第一个参数
    class C:
        @staticmethod
        def f(arg1, arg2, ...): ...

8.文件操作

  1. open(file, mode='r', encoding=None):开 file 并返回对应的 file object

 

标签:__,10,内置,函数,返回,object,print,100,iterable
From: https://www.cnblogs.com/victor1234/p/16852806.html

相关文章

  • Codeforces Round #610 (Div. 2) C
    C.PetyaandExamhttps://codeforces.com/contest/1282/problem/C考虑贪心先对于时间排序然后贪心我们可以不考那我们可以在此之前离开然后在离开之前这段时间多做......
  • 推荐10本大数据领域必读的经典好书(火速收藏)
        写博客也已经快一年了,从去年的1024到现在金秋10月已纷至沓来。回顾这一年所发布的原创文章,基本都是与大数据主流或者周边的技术为主。本篇博客,就为大家介绍几篇......
  • 机器学习100天( 100-Days-Of-ML-Code )中文版
    机器学习AI算法工程 公众号: datayx完整版下载地址获取:关注微信公众号datayx 然后回复 100  即可获取。数据预处理|第1天数据预处理实现简单线性回归|第2天简单......
  • 函数式接口与lambda表达式
    函数式接口:只有一个方法的接口publicinterfaceCanAdd{intadd(inta,intb);}该接口作为其他方法的入参,实现函数传递publicclassDog{publicstatic......
  • 免费服务器分享20221103
    今天再次安装了免费服务器,来和大家分享一下。三丰云是一个提供免费云服务器的服务商,包括"免费虚拟主机"、“免费云服务器”。挺良心的,只不过需要大家发圈,但是功能实在......
  • Android10 dex2oat实践
    最近看到一篇博客:Android性能优化之Android10+dex2oat实践,对这个优化很感兴趣,打算研究研究能否接入到项目中。不过该博客只讲述了思路,没有给完整源码。本项目参考该博......
  • JVM 常见线上问题 → CPU 100%、内存泄露 问题排查
    开心一刻明明是个小bug,但就是死活修不好,我特么心态崩了......前言Windows后文中用到了两个工具:​​ProcessorExplorer​​​、​​MAT​​,它们是什么,有什么用,怎么用,本......
  • 平均110万个漏洞被积压,企业漏洞管理状况堪忧
    在软件安全的世界中,企业在软件开发生命周期中都面临着漏洞带来的巨大挑战。开发人员每天都需要确保交付没有漏洞的代码,因此他们需要花费大量的时间来解决首要处理的漏洞问......
  • 列出100以内的素数
    1#include<stdio.h>2intmain()3{4intx;5for(x=2;x<100;x++)6{7inti;8intisPrime=1;9for(i=2;i<x;i+......
  • 函数
    简单函数的定义,形参可有可无,返回值可有可无1packagemain23import"fmt"45funcmain(){6res,res2:=test5()7fmt.Println(res+res2)......