草庐IT

Python | 内置函数(BIF)

大灰狼 | TcDhl`s Blog 2023-03-28 原文

Python内置函数 | V3.9.1 | 共计155个

还没学完, 还没记录完, 不知道自己能不能坚持记录下去


1.ArithmeticError 2.AssertionError 3.AttributeError 4.BaseException 5.BlockingIOError
6.BrokenPipeError 7.BufferError 8.BytesWarning 9.ChildProcessError 10.ConnectionAbortedError
11.ConnectionError 12.ConnectionRefusedError 13.ConnectionResetError 14.DeprecationWarning 15.EOFError
16.Ellipsis 17.EnvironmentError 18.Exception 19.False 20.FileExistsError
21.FileNotFoundError 22.FloatingPointError 23.FutureWarning 24.GeneratorExit 25.IOError
26.ImportError 27.ImportWarning 28.IndentationError 29.IndexError 30.InterruptedError
31.IsADirectoryError 32.KeyError 33.KeyboardInterrupt 34.LookupError 35.MemoryError
36.ModuleNotFoundError 37.NameError 38.None 39.NotADirectoryError 40.NotImplemented
41.NotImplementedError 42.OSError 43.OverflowError 44.PendingDeprecationWarning 45.PermissionError
46.ProcessLookupError 47.RecursionError 48.ReferenceError 49.ResourceWarning 50.RuntimeError
51.RuntimeWarning 52.StopAsyncIteration 53.StopIteration 54.SyntaxError 55.SyntaxWarning
56.SystemError 57.SystemExit 58.TabError 59.TimeoutError 60.True
61.TypeError 62.UnboundLocalError 63.UnicodeDecodeError 64.UnicodeEncodeError 65.UnicodeError
66.UnicodeTranslateError 67.UnicodeWarning 68.UserWarning 69.ValueError 70.Warning
71.WindowsError 72.ZeroDivisionError 73.__build_class__ 74.__debug__ 75.__doc__
76.__import__ 77.__loader__ 78.__name__ 79.__package__ 80.__spec__
81.abs 82.all 83.any 84.ascii 85.bin
86.bool 87.breakpoint 88.bytearray 89.bytes 90.callable
91.chr 92.classmethod 93.compile 94.complex 95.copyright
96.credits 97.delattr 98.dict 99.dir 100.divmod
101.enumerate 102.eval 103.exec 104.execfile 105.exit
106.filter 107.float 108.format 109.frozenset 110.getattr
111.globals 112.hasattr 113.hash 114help 115.hex
116.id 117.input 118.int 119.isinstance 120.issubclass
121.iter 122.len 123.license 124.list 125.locals
126.map 127.max 128.memoryview 129.min 130.next
131.object 132.oct 133.open 134.ord 135.pow
136.print 137.property 138.quit 139.range 140.repr
141.reversed 142.round 143.runfile 144.set 145.setattr
146.slice 147.sorted 148.staticmethod 149.str 150.sum
151.super 152.tuple 153.type 154.vars 155.zip

1.ArithmeticError

2.AssertionError

3.AttributeError

4.BaseException

5.BlockingIOError

6.BrokenPipeError

7.BufferError

8.BytesWarning

9.ChildProcessError

10.ConnectionAbortedError

11.ConnectionError

12.ConnectionRefusedError

13.ConnectionResetError

14.DeprecationWarning

15.EOFError

16.Ellipsis

17.EnvironmentError

18.Exception

19.False

20.FileExistsError

21.FileNotFoundError

22.FloatingPointError

23.FutureWarning

24.GeneratorExit

25.IOError

26.ImportError

27.ImportWarning

28.IndentationError

29.IndexError

30.InterruptedError

31.IsADirectoryError

32.KeyError

33.KeyboardInterrupt

34.LookupError

35.MemoryError

36.ModuleNotFoundError

37.NameError

38.None

39.NotADirectoryError

40.NotImplemented

41.NotImplementedError

42.OSError

43.OverflowError

44.PendingDeprecationWarning

45.PermissionError

46.ProcessLookupError

47.RecursionError

48.ReferenceError

49.ResourceWarning

50.RuntimeError

51.RuntimeWarning

52.StopAsyncIteration

53.StopIteration

54.SyntaxError

55.SyntaxWarning

56.SystemError

57.SystemExit

58.TabError

59.TimeoutError

60.True

61.TypeError

62.UnboundLocalError

63.UnicodeDecodeError

64.UnicodeEncodeError

65.UnicodeError

66.UnicodeTranslateError

67.UnicodeWarning

68.UserWarning

69.ValueError

70.Warning

71.WindowsError

72.ZeroDivisionError

73.__build_class__

74.__debug__

75.__doc__

76.__import__

77.__loader__

78.__name__

79.__package__

80.__spec__

81.abs

82.all

83.any

84.ascii

85.bin

86.bool

87.breakpoint

88.bytearray

89.bytes

90.callable

91.chr

92.classmethod

修饰符:类方法 @classmethod | 无需显式地传递类名做实参

class Computer:
    # 类属性modules
    __modules = {"cpu":"Intel", "内存":"镁光", "硬盘":"970-Pro"}

    # 设定修饰符@类方法 | 类的函数或者叫类的方法output_modules
    @classmethod
    def output_modules(cls):
        for (i,s) in cls.__modules.items():
            print(i, ':', s)

# 调用类的方法output_modules,无需显式地传递类名做实参
Computer.output_modules()

#-------------------------------------------------------------
# 输出结果:
# cpu : Intel
# 内存 : 镁光
# 硬盘 : 970-Pro

也可被其他类直接进行调用(感觉有点全局的意思), 看例子代码如下:

class Computer:
    # 类属性modules
    __modules = {"cpu":"Intel", "内存":"镁光", "硬盘":"970-Pro"}

    # 设定修饰符@类方法 | 类的函数或者叫类的方法output_modules
    @classmethod
    def output_modules(cls):
        for (i,s) in cls.__modules.items():
            print(i, ':', s)


class OtherClass:
    def __init__(self):
        pass
    def _test_OtherClass(self):
        # 调用类的方法output_modules,无需显式地传递类名做实参
        Computer.output_modules()

aaaa = OtherClass()
aaaa._test_OtherClass()

#-------------------------------------------------------------
# 输出结果:
# cpu : Intel
# 内存 : 镁光
# 硬盘 : 970-Pro

93.compile

94.complex

95.copyright

96.credits

97.delattr

98.dict

99.dir

100.divmod

101.enumerate

102.eval

103.exec

104.execfile

105.exit

106.filter

107.float

108.format

109.frozenset

110.getattr

111.globals

112.hasattr

113.hash

114help

115.hex

116.id

117.input

118.int

119.isinstance

120.issubclass

121.iter

122.len

123.license

124.list

125.locals

126.map

127.max

128.memoryview

129.min

131.object

132.oct

133.open

134.ord

135.pow

136.print

137.property

此修饰符可赋值给变量, 语法为:x = property(getx, setx, delx)

  • 如果是以此种方法的话, 函数名或者说是方法名可以不相同

如果是以装饰器形式使用的话, 函数名或者说是方法名必须相同, 例子代码如下:

class Computer:
    # 类属性 __modules
    __modules = {"cpu":"Intel", "内存":"镁光", "硬盘":"970-Pro"}
    
    def __init__(self):
        pass

    # 获取字典的key
    @property
    def modules_property(self):
        # 字典 __modules的key 取出来变成列表
        __loops = [i for i in self.__modules]

        for ii in range(len(self.__modules)):
            print(__loops[ii], ':', self.__modules[__loops[ii]])

    # 给字典新增数据
    @modules_property.setter
    def modules_property(self, key_value):
        self.__modules[key_value[0]] = key_value[1]

    # 删除字典中内容, 这里没办法通过@modules_property.deleter以达到删除字典中某个键值
    # 所以换成了 静态方法 来删除键值
    @staticmethod
    def del_modules_property(__del, key):
        try:
            # dels.__modules.pop(key, 'Error, 删除的内容不存在!')
            __del.__modules.pop(key)
        except KeyError:
            print(f'Error, 删除的键: {key} 不存在!')# 这个引用变量 应该在v3.6版本以下不兼容...
            # print('Error, 删除的键: {keys} 不存在!'.format(keys=key))

# 实例化类
aaaa = Computer()

print('打印原有字典内容')
aaaa.modules_property
print('----------分隔符-----------')

print('打印新增后字典内容')
# 通过@modules_property.setter, 给字典新增数据
aaaa.modules_property = ('机箱', '海盗船')
# 通过@property,其实也是@getattr, 取出字典中的键值内容
aaaa.modules_property
print('----------分隔符-----------')

print('打印删除后字典内容')
# 通过静态方法@staticmethod, 删除字典中某个元素,或者说成删除字典中某个键值内容
Computer.del_modules_property(Computer, 'cpu')
# 通过@property, 再次打印字典内容,看下是否正常删除了
aaaa.modules_property

# -------------------------------------------------------------
# 打印原有字典内容
# cpu : Intel
# 内存 : 镁光
# 硬盘 : 970-Pro
# ----------分隔符-----------
# 打印新增后字典内容
# cpu : Intel
# 内存 : 镁光
# 硬盘 : 970-Pro
# 机箱 : 海盗船
# ----------分隔符-----------
# 打印删除后字典内容
# 内存 : 镁光
# 硬盘 : 970-Pro
# 机箱 : 海盗船

2022-06-01 推翻例子中"删除字典中内容, 这里没办法通过@modules_property.deleter以达到删除字典中某个键值"这句话:

class Computer:
    def __init__(self) -> None:

        self.modules = {"cpu":"intel", "内存":"镁光", "硬盘":"970-pro"}

        self.moduleslist = []


    @property
    def modulesGetSetDel(self):
        self.moduleslist.clear()
        get_loops = [i for i in self.modules]

        for ii in range(len(self.modules)):

            self.moduleslist.append(get_loops[ii] + ": " + self.modules[get_loops[ii]])
        return self.moduleslist


    @modulesGetSetDel.setter
    def modulesGetSetDel(self, key_value):

        self.get_key_value_loops = [i for i in key_value]
        for i in range(len(self.get_key_value_loops)):
            self.modules[self.get_key_value_loops[i]] =  key_value[self.get_key_value_loops[i]]


    @modulesGetSetDel.deleter
    def modulesGetSetDel(self):
        for i in range(len(self.get_key_value_loops)):
            del self.modules[self.get_key_value_loops[i]]


aa = Computer()

# #打印原始字典
print("原始字典数据: ", aa.modulesGetSetDel)

# #打印新增的字典
aa.modulesGetSetDel = {"机箱":"海盗船", "测试1":"测试11"}
print("新增字典数据: ", aa.modulesGetSetDel)

# 打印删除后的字典数据
del aa.modulesGetSetDel
print("删后字典数据: ", aa.modulesGetSetDel)

# -------------------------------------------------------------
# 原始字典数据:  ['cpu: intel', '内存: 镁光', '硬盘: 970-pro']
# 新增字典数据:  ['cpu: intel', '内存: 镁光', '硬盘: 970-pro', '机箱: 海盗船', '测试1: 测试11']
# 删后字典数据:  ['cpu: intel', '内存: 镁光', '硬盘: 970-pro']

138.quit

139.range

140.repr

141.reversed

142.round

143.runfile

144.set

145.setattr

146.slice

147.sorted

148.staticmethod

# 修饰符:静态方法 @staticmethod | 必须显式地传递类名做实参

class Computer:
    # 类属性modules
    __modules = {"cpu":"Intel", "内存":"镁光", "硬盘":"970-Pro"}

    # 在静态方法search_module中定义形参var,准备传递类:Computer
    # 调用时必须显性地传递类名,才能实现类方法一样的效果
    # 设定修饰符@静态方法 | 类的函数或者叫类的方法search_module
    @staticmethod
    def search_module(var, module_value):
        print(var.__modules[module_value])

Computer.search_module(Computer, "cpu")
Computer.search_module(Computer, "内存")
Computer.search_module(Computer, "硬盘")

#-------------------------------------------------------------
# 输出结果:
# Intel
# 镁光
# 970-Pro

也可被其他类直接进行调用(有点全局的意思.....), 看例子代码如下:

class Computer:
    # 类属性modules
    __modules = {"cpu":"Intel", "内存":"镁光", "硬盘":"970-Pro"}

    # 在静态方法search_module中定义形参var,准备传递类:Computer
    # 调用时必须显性地传递类名,才能实现类方法一样的效果
    # 设定修饰符@静态方法 | 类的函数或者叫类的方法search_module
    @staticmethod
    def search_module(var, module_value):
        print(var.__modules[module_value])


class OtherClass:
    def __init__(self):
        pass

    def _test_OtherClass(self):
        # 调用类的静态方法search_module,必须显式地传递类名做实参
        Computer.search_module(Computer, "cpu")
        Computer.search_module(Computer, "内存")
        Computer.search_module(Computer, "硬盘")

aaaa = OtherClass()
aaaa._test_OtherClass()

#-------------------------------------------------------------
# 输出结果:
# Intel
# 镁光
# 970-Pro

149.str

150.sum

151.super

super函数不需要明确的给出任何 "被调用类" 的名称, 学习中觉得 子类-父类-超类 叫起来很绕, 就自认为叫成 "被调用类" 方便自己理解

  • 假设定义了三个类: A B C
  • 类A 继承 类B, 类A 是 类B 的子类 | 类B 是 类A 的父类(被调用类)
  • 类B 继承 类C, 类B 是 类C 的子类 | 类C 是 类B 的父类(被调用类)
  • 类A 间接继承 类C , 类C 是 类A 的超类(被调用类)
  • 例子待定

152.tuple

153.type

154.vars

155.zip

有关Python | 内置函数(BIF)的更多相关文章

  1. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  3. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  4. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  5. Python 相当于 Perl/Ruby ||= - 2

    这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。

  6. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  7. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  8. 华为OD机试用Python实现 -【明明的随机数】 2023Q1A - 2

    华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o

  9. python - 如何读取 MIDI 文件、更改其乐器并将其写回? - 2

    我想解析一个已经存在的.mid文件,改变它的乐器,例如从“acousticgrandpiano”到“violin”,然后将它保存回去或作为另一个.mid文件。根据我在文档中看到的内容,该乐器通过program_change或patch_change指令进行了更改,但我找不到任何在已经存在的MIDI文件中执行此操作的库.他们似乎都只支持从头开始创建的MIDI文件。 最佳答案 MIDIpackage会为您完成此操作,但具体方法取决于midi文件的原始内容。一个MIDI文件由一个或多个音轨组成,每个音轨是十六个channel中任何一个上的

  10. 「Python|Selenium|场景案例」如何定位iframe中的元素? - 2

    本文主要介绍在使用Selenium进行自动化测试或者任务时,对于使用了iframe的页面,如何定位iframe中的元素文章目录场景描述解决方案具体代码场景描述当我们在使用Selenium进行自动化测试的时候,可能会遇到一些界面或者窗体是使用HTML的iframe标签进行承载的。对于iframe中的标签,如果直接查找是无法找到的,会抛出没有找到元素的异常。比如近在咫尺的例子就是,CSDN的登录窗体就是使用的iframe,大家可以尝试通过F12开发者模式查看到的tag_name,class_name,id或者xpath来定位中的页面元素,会抛出NoSuchElementException异常。解决

随机推荐