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 你好

     


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM