python内置方法大全

数学运算

类型转换

序列操作

对象操作

  • help:返回对象的帮助信息
  •  1 >>> help(str) 
     2 Help on class str in module builtins:
     3 
     4 class str(object)
     5  |  str(object='') -> str
     6  |  str(bytes_or_buffer[, encoding[, errors]]) -> str
     7  |  
     8  |  Create a new string object from the given object. If encoding or
     9  |  errors is specified, then the object must expose a data buffer
    10  |  that will be decoded using the given encoding and error handler.
    11  |  Otherwise, returns the result of object.__str__() (if defined)
    12  |  or repr(object).
    13  |  encoding defaults to sys.getdefaultencoding().
    14  |  errors defaults to 'strict'.
    15  |  
    16  |  Methods defined here:
    17  |  
    18  |  __add__(self, value, /)
    19  |      Return self+value.
    20  |  
    21   ***************************
  • dir:返回对象或者当前作用域内的属性列表
    1 >>> import math
    2 >>> math
    3 <module 'math' (built-in)>
    4 >>> dir(math)
    5 ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
  • id:返回对象的唯一标识符
    1 >>> a = 'some text'
    2 >>> id(a)
    3 69228568
  • hash:获取对象的哈希值
    1 >>> hash('good good study')
    2 1032709256
  • type:返回对象的类型,或者根据传入的参数创建一个新的类型
    1 >>> type(1) # 返回对象的类型
    2 <class 'int'>
    3 
    4 #使用type函数创建类型D,含有属性InfoD
    5 >>> D = type('D',(A,B),dict(InfoD='some thing defined in D'))
    6 >>> d = D()
    7 >>> d.InfoD
    8  'some thing defined in D'
  • len:返回对象的长度
    1 >>> len('abcd') # 字符串
    2 >>> len(bytes('abcd','utf-8')) # 字节数组
    3 >>> len((1,2,3,4)) # 元组
    4 >>> len([1,2,3,4]) # 列表
    5 >>> len(range(1,5)) # range对象
    6 >>> len({'a':1,'b':2,'c':3,'d':4}) # 字典
    7 >>> len({'a','b','c','d'}) # 集合
    8 >>> len(frozenset('abcd')) #不可变集合
  • ascii:返回对象的可打印表字符串表现方式
    1 >>> ascii(1)
    2 '1'
    3 >>> ascii('&')
    4 "'&'"
    5 >>> ascii(9000000)
    6 '9000000'
    7 >>> ascii('中文') #非ascii字符
    8 "'\u4e2d\u6587'"
  • format:格式化显示值
     1 #字符串可以提供的参数 's' None
     2 >>> format('some string','s')
     3 'some string'
     4 >>> format('some string')
     5 'some string'
     6 
     7 #整形数值可以提供的参数有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None
     8 >>> format(3,'b') #转换成二进制
     9 '11'
    10 >>> format(97,'c') #转换unicode成字符
    11 'a'
    12 >>> format(11,'d') #转换成10进制
    13 '11'
    14 >>> format(11,'o') #转换成8进制
    15 '13'
    16 >>> format(11,'x') #转换成16进制 小写字母表示
    17 'b'
    18 >>> format(11,'X') #转换成16进制 大写字母表示
    19 'B'
    20 >>> format(11,'n') #和d一样
    21 '11'
    22 >>> format(11) #默认和d一样
    23 '11'
    24 
    25 #浮点数可以提供的参数有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None
    26 >>> format(314159267,'e') #科学计数法,默认保留6位小数
    27 '3.141593e+08'
    28 >>> format(314159267,'0.2e') #科学计数法,指定保留2位小数
    29 '3.14e+08'
    30 >>> format(314159267,'0.2E') #科学计数法,指定保留2位小数,采用大写E表示
    31 '3.14E+08'
    32 >>> format(314159267,'f') #小数点计数法,默认保留6位小数
    33 '314159267.000000'
    34 >>> format(3.14159267000,'f') #小数点计数法,默认保留6位小数
    35 '3.141593'
    36 >>> format(3.14159267000,'0.8f') #小数点计数法,指定保留8位小数
    37 '3.14159267'
    38 >>> format(3.14159267000,'0.10f') #小数点计数法,指定保留10位小数
    39 '3.1415926700'
    40 >>> format(3.14e+1000000,'F')  #小数点计数法,无穷大转换成大小字母
    41 'INF'
    42 
    43 #g的格式化比较特殊,假设p为格式中指定的保留小数位数,先尝试采用科学计数法格式化,得到幂指数exp,如果-4<=exp<p,则采用小数计数法,并保留p-1-exp位小数,否则按小数计数法计数,并按p-1保留小数位数
    44 >>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点
    45 '3e-05'
    46 >>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留1位小数点
    47 '3.1e-05'
    48 >>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留2位小数点
    49 '3.14e-05'
    50 >>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点,E使用大写
    51 '3.14E-05'
    52 >>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留0位小数点
    53 '3'
    54 >>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留1位小数点
    55 '3.1'
    56 >>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留2位小数点
    57 '3.14'
    58 >>> format(0.00003141566,'.1n') #和g相同
    59 '3e-05'
    60 >>> format(0.00003141566,'.3n') #和g相同
    61 '3.14e-05'
    62 >>> format(0.00003141566) #和g相同
    63 '3.141566e-05'
  • vars:返回当前作用域内的局部变量和其值组成的字典,或者返回对象的属性列表
     1 #作用于类实例
     2 >>> class A(object):
     3     pass
     4 
     5 >>> a.__dict__
     6 {}
     7 >>> vars(a)
     8 {}
     9 >>> a.name = 'Kim'
    10 >>> a.__dict__
    11 {'name': 'Kim'}
    12 >>> vars(a)
    13 {'name': 'Kim'}

反射操作

  • __import__:动态导入模块
    1 index = __import__('index')
    2 index.sayHello()
  • isinstance:判断对象是否是类或者类型元组中任意类元素的实例
    1 >>> isinstance(1,int)
    2 True
    3 >>> isinstance(1,str)
    4 False
    5 >>> isinstance(1,(int,str))
    6 True
  • issubclass:判断类是否是另外一个类或者类型元组中任意类元素的子类
    1 >>> issubclass(bool,int)
    2 True
    3 >>> issubclass(bool,str)
    4 False
    5 
    6 >>> issubclass(bool,(str,int))
    7 True
  • hasattr:检查对象是否含有属性
     1 #定义类A
     2 >>> class Student:
     3     def __init__(self,name):
     4         self.name = name
     5 
     6         
     7 >>> s = Student('Aim')
     8 >>> hasattr(s,'name') #a含有name属性
     9 True
    10 >>> hasattr(s,'age') #a不含有age属性
    11 False
  • getattr:获取对象的属性值
     1 #定义类Student
     2 >>> class Student:
     3     def __init__(self,name):
     4         self.name = name
     5 
     6 >>> getattr(s,'name') #存在属性name
     7 'Aim'
     8 
     9 >>> getattr(s,'age',6) #不存在属性age,但提供了默认值,返回默认值
    10 
    11 >>> getattr(s,'age') #不存在属性age,未提供默认值,调用报错
    12 Traceback (most recent call last):
    13   File "<pyshell#17>", line 1, in <module>
    14     getattr(s,'age')
    15 AttributeError: 'Stduent' object has no attribute 'age'
  • setattr:设置对象的属性值
     1 >>> class Student:
     2     def __init__(self,name):
     3         self.name = name
     4 
     5         
     6 >>> a = Student('Kim')
     7 >>> a.name
     8 'Kim'
     9 >>> setattr(a,'name','Bob')
    10 >>> a.name
    11 'Bob'
  • delattr:删除对象的属性
     1 #定义类A
     2 >>> class A:
     3     def __init__(self,name):
     4         self.name = name
     5     def sayHello(self):
     6         print('hello',self.name)
     7 
     8 #测试属性和方法
     9 >>> a.name
    10 '小麦'
    11 >>> a.sayHello()
    12 hello 小麦
    13 
    14 #删除属性
    15 >>> delattr(a,'name')
    16 >>> a.name
    17 Traceback (most recent call last):
    18   File "<pyshell#47>", line 1, in <module>
    19     a.name
    20 AttributeError: 'A' object has no attribute 'name'
  • callable:检测对象是否可被调用
     1 >>> class B: #定义类B
     2     def __call__(self):
     3         print('instances are callable now.')
     4 
     5         
     6 >>> callable(B) #类B是可调用对象
     7 True
     8 >>> b = B() #调用类B
     9 >>> callable(b) #实例b是可调用对象
    10 True
    11 >>> b() #调用实例b成功
    12 instances are callable now.

变量操作

  • globals:返回当前作用域内的全局变量和其值组成的字典
    1 >>> globals()
    2 {'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
    3 >>> a = 1
    4 >>> globals() #多了一个a
    5 {'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, 'a': 1, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
  • locals:返回当前作用域内的局部变量和其值组成的字典
     1 >>> def f():
     2     print('before define a ')
     3     print(locals()) #作用域内无变量
     4     a = 1
     5     print('after define a')
     6     print(locals()) #作用域内有一个a变量,值为1
     7 
     8     
     9 >>> f
    10 <function f at 0x03D40588>
    11 >>> f()
    12 before define a 
    13 {} 
    14 after define a
    15 {'a': 1}

交互操作

文件操作

编译执行

装饰器

  • property:标示属性的装饰器
     1 >>> class C:
     2     def __init__(self):
     3         self._name = ''
     4     @property
     5     def name(self):
     6         """i'm the 'name' property."""
     7         return self._name
     8     @name.setter
     9     def name(self,value):
    10         if value is None:
    11             raise RuntimeError('name can not be None')
    12         else:
    13             self._name = value
    14 
    15             
    16 >>> c = C()
    17 
    18 >>> c.name # 访问属性
    19 ''
    20 >>> c.name = None # 设置属性时进行验证
    21 Traceback (most recent call last):
    22   File "<pyshell#84>", line 1, in <module>
    23     c.name = None
    24   File "<pyshell#81>", line 11, in name
    25     raise RuntimeError('name can not be None')
    26 RuntimeError: name can not be None
    27 
    28 >>> c.name = 'Kim' # 设置属性
    29 >>> c.name # 访问属性
    30 'Kim'
    31 
    32 >>> del c.name # 删除属性,不提供deleter则不能删除
    33 Traceback (most recent call last):
    34   File "<pyshell#87>", line 1, in <module>
    35     del c.name
    36 AttributeError: can't delete attribute
    37 >>> c.name
    38 'Kim'
  • classmethod:标示方法为类方法的装饰器
     1 >>> class C:
     2     @classmethod
     3     def f(cls,arg1):
     4         print(cls)
     5         print(arg1)
     6 
     7         
     8 >>> C.f('类对象调用类方法')
     9 <class '__main__.C'>
    10 类对象调用类方法
    11 
    12 >>> c = C()
    13 >>> c.f('类实例对象调用类方法')
    14 <class '__main__.C'>
    15 类实例对象调用类方法
  • staticmethod:标示方法为静态方法的装饰器
     1 # 使用装饰器定义静态方法
     2 >>> class Student(object):
     3     def __init__(self,name):
     4         self.name = name
     5     @staticmethod
     6     def sayHello(lang):
     7         print(lang)
     8         if lang == 'en':
     9             print('Welcome!')
    10         else:
    11             print('你好!')
    12 
    13             
    14 >>> Student.sayHello('en') #类调用,'en'传给了lang参数
    15 en
    16 Welcome!
    17 
    18 >>> b = Student('Kim')
    19 >>> b.sayHello('zh')  #类实例对象调用,'zh'传给了lang参数
    20 zh
    21 你好
原文地址:https://www.cnblogs.com/sun-10387834/p/10333563.html