數學運算
- abs:求數值的絕對值
1 >>> abs(-2) 2 2
- divmod:返回兩個數值的商和余數
1 >>> divmod(5,2) 2 (2, 1) 3 >> divmod(5.5,2) 4 (2.0, 1.5)
- max:返回可迭代對象中的元素中的最大值或者所有參數的最大值
1 >>> max(1,2,3) # 傳入3個參數 取3個中較大者 2 3 3 >>> max('1234') # 傳入1個可迭代對象,取其最大元素值 4 '4' 5 6 >>> max(-1,0) # 數值默認去數值較大者 7 0 8 >>> max(-1,0,key = abs) # 傳入了求絕對值函數,則參數都會進行求絕對值后再取較大者 9 -1
- min:返回可迭代對象中的元素中的最小值或者所有參數的最小值
1 >>> min(1,2,3) # 傳入3個參數 取3個中較小者 2 1 3 >>> min('1234') # 傳入1個可迭代對象,取其最小元素值 4 '1' 5 6 >>> min(-1,-2) # 數值默認去數值較小者 7 -2 8 >>> min(-1,-2,key = abs) # 傳入了求絕對值函數,則參數都會進行求絕對值后再取較小者 9 -1
- pow:返回兩個數值的冪運算值或其與指定整數的模值
1 >>> pow(2,3) 2 >>> 2**3 3 8 4 >>> pow(2,3,5) 5 >>> pow(2,3)%5
6 3 - round:對浮點數進行四舍五入求值
1 >>> round(1.1314926,1) 2 1.1 3 >>> round(1.1314926,5) 4 1.13149
- sum:對元素類型是數值的可迭代對象中的每個元素求和
-
1 # 傳入可迭代對象 2 >>> sum((1,2,3,4)) 3 10 4 # 元素類型必須是數值型 5 >>> sum((1.5,2.5,3.5,4.5)) 6 12.0 7 >>> sum((1,2,3,4),-10) 8 0
類型轉換
- bool:根據傳入的參數的邏輯值創建一個新的布爾值
1 >>> bool() #未傳入參數 2 False 3 >>> bool(0) #數值0、空序列等值為False 4 False 5 >>> bool(1) 6 True
- int:根據傳入的參數創建一個新的整數
1 >>> int() #不傳入參數時,得到結果0。 2 0 3 >>> int(3) 4 3 5 >>> int(3.6) 6 3
- float:根據傳入的參數創建一個新的浮點數
1 >>> float() #不提供參數的時候,返回0.0 2 0.0 3 >>> float(3) 4 3.0 5 >>> float('3') 6 3.0
- complex:根據傳入參數創建一個新的復數
1 >>> complex() #當兩個參數都不提供時,返回復數 0j。 2 0j 3 >>> complex('1+2j') #傳入字符串創建復數 4 (1+2j) 5 >>> complex(1,2) #傳入數值創建復數 6 (1+2j)
- str:返回一個對象的字符串表現形式(給用戶)
1 >>> str() 2 '' 3 >>> str(None) 4 'None' 5 >>> str('abc') 6 'abc' 7 >>> str(123) 8 '123'
- bytearray:根據傳入的參數創建一個新的字節數組
1 >>> bytearray('中文','utf-8') 2 bytearray(b'\xe4\xb8\xad\xe6\x96\x87')
- bytes:根據傳入的參數創建一個新的不可變字節數組
1 >>> bytes('中文','utf-8') 2 b'\xe4\xb8\xad\xe6\x96\x87'
- memoryview:根據傳入的參數創建一個新的內存查看對象
1 >>> v = memoryview(b'abcefg') 2 >>> v[1] 3 98 4 >>> v[-1] 5 103
- ord:返回Unicode字符對應的整數
1 >>> ord('a') 2 97
- chr:返回整數所對應的Unicode字符
1 >>> chr(97) #參數類型為整數 2 'a'
- bin:將整數轉換成2進制字符串
1 >>> bin(3) 2 '0b11'
- oct:將整數轉化成8進制數字符串
1 >>> oct(10) 2 '0o12'
- hex:將整數轉換成16進制字符串
1 >>> hex(15) 2 '0xf'
- tuple:根據傳入的參數創建一個新的元組
1 >>> tuple() #不傳入參數,創建空元組 2 () 3 >>> tuple('121') #傳入可迭代對象。使用其元素創建新的元組 4 ('1', '2', '1')
- list:根據傳入的參數創建一個新的列表
1 >>>list() # 不傳入參數,創建空列表 2 [] 3 >>> list('abcd') # 傳入可迭代對象,使用其元素創建新的列表 4 ['a', 'b', 'c', 'd']
- dict:根據傳入的參數創建一個新的字典
1 >>> dict() # 不傳入任何參數時,返回空字典。 2 {} 3 >>> dict(a = 1,b = 2) # 可以傳入鍵值對創建字典。 4 {'b': 2, 'a': 1} 5 >>> dict(zip(['a','b'],[1,2])) # 可以傳入映射函數創建字典。 6 {'b': 2, 'a': 1} 7 >>> dict((('a',1),('b',2))) # 可以傳入可迭代對象創建字典。 8 {'b': 2, 'a': 1}
- set:根據傳入的參數創建一個新的集合
1 >>>set() # 不傳入參數,創建空集合 2 set() 3 >>> a = set(range(10)) # 傳入可迭代對象,創建集合 4 >>> a 5 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
- frozenset:根據傳入的參數創建一個新的不可變集合
1 >>> a = frozenset(range(10)) 2 >>> a 3 frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
- enumerate:根據可迭代對象創建枚舉對象
1 >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] 2 >>> list(enumerate(seasons)) 3 [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] 4 >>> list(enumerate(seasons, start=1)) #指定起始值 5 [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
- range:根據傳入的參數創建一個新的range對象
1 >>> a = range(10) 2 >>> b = range(1,10) 3 >>> c = range(1,10,3) 4 >>> a,b,c # 分別輸出a,b,c 5 (range(0, 10), range(1, 10), range(1, 10, 3)) 6 >>> list(a),list(b),list(c) # 分別輸出a,b,c的元素 7 ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 4, 7])
- iter:根據傳入的參數創建一個新的可迭代對象
1 >>> a = iter('abcd') #字符串序列 2 >>> a 3 <str_iterator object at 0x03FB4FB0> 4 >>> next(a) 5 'a' 6 >>> next(a) 7 'b' 8 >>> next(a) 9 'c' 10 >>> next(a) 11 'd' 12 >>> next(a) 13 Traceback (most recent call last): 14 File "<pyshell#29>", line 1, in <module> 15 next(a) 16 StopIteration
- slice:根據傳入的參數創建一個新的切片對象
1 >>> c1 = slice(5) # 定義c1 2 >>> c1 3 slice(None, 5, None) 4 >>> c2 = slice(2,5) # 定義c2 5 >>> c2 6 slice(2, 5, None) 7 >>> c3 = slice(1,10,3) # 定義c3 8 >>> c3 9 slice(1, 10, 3)
#使用方式
s=slice(1,5,2) #一次定義多次可用
list1=[1,2,3,4,5,6,7,8,9]
print(list1[s]) - super:根據傳入的參數創建一個新的子類和父類關系的代理對象
1 #定義父類A 2 >>> class A(object): 3 def __init__(self): 4 print('A.__init__') 5 6 #定義子類B,繼承A 7 >>> class B(A): 8 def __init__(self): 9 print('B.__init__') 10 super().__init__() #super調用不需要放在首行 11 12 #super調用父類方法 13 >>> b = B() 14 B.__init__ 15 A.__init__
- object:創建一個新的object對象
1 >>> a = object() 2 >>> a.name = 'kim' # 不能設置屬性 3 Traceback (most recent call last): 4 File "<pyshell#9>", line 1, in <module> 5 a.name = 'kim' 6 AttributeError: 'object' object has no attribute 'name'
序列操作
- all:判斷可迭代對象的每個元素是否都為True值
1 >>> all([1,2]) #列表中每個元素邏輯值均為True,返回True 2 True 3 >>> all([0,1,2]) #列表中0的邏輯值為False,返回False 4 False 5 >>> all(()) #空元組 6 True 7 >>> all({}) #空字典 8 True
- any:判斷可迭代對象的元素是否有為True值的元素
1 >>> any([0,1,2]) #列表元素有一個為True,則返回True 2 True 3 >>> any([0,0]) #列表元素全部為False,則返回False 4 False 5 >>> any([]) #空列表 6 False 7 >>> any({}) #空字典 8 False
- f ilter:使用指定方法過濾可迭代對象的元素
1 >>> a = list(range(1,10)) #定義序列 2 >>> a 3 [1, 2, 3, 4, 5, 6, 7, 8, 9] 4 >>> def if_odd(x): #定義奇數判斷函數 5 return x%2==1 6 7 >>> list(filter(if_odd,a)) #篩選序列中的奇數 8 [1, 3, 5, 7, 9]
- map:使用指定方法去作用傳入的每個可迭代對象的元素,生成新的可迭代對象
1 >>> a = map(ord,'abcd') 2 >>> a 3 <map object at 0x03994E50> 4 >>> list(a) 5 [97, 98, 99, 100]
- next:返回可迭代對象中的下一個元素值
1 >>> a = iter('abcd') 2 >>> next(a) 3 'a' 4 >>> next(a) 5 'b' 6 >>> next(a) 7 'c' 8 >>> next(a) 9 'd' 10 >>> next(a) 11 Traceback (most recent call last): 12 File "<pyshell#18>", line 1, in <module> 13 next(a) 14 StopIteration 15 16 #傳入default參數后,如果可迭代對象還有元素沒有返回,則依次返回其元素值,如果所有元素已經返回,則返回default指定的默認值而不拋出StopIteration 異常 17 >>> next(a,'e') 18 'e' 19 >>> next(a,'e') 20 'e'
- reversed:反轉序列生成新的可迭代對象
1 >>> a = reversed(range(10)) # 傳入range對象 2 >>> a # 類型變成迭代器 3 <range_iterator object at 0x035634E8> 4 >>> list(a) 5 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
- sorted:對可迭代對象進行排序,返回一個新的列表
1 >>> a = ['a','b','d','c','B','A'] 2 >>> a 3 ['a', 'b', 'd', 'c', 'B', 'A'] 4 5 >>> sorted(a) # 默認按字符ascii碼排序 6 ['A', 'B', 'a', 'b', 'c', 'd'] 7 8 >>> sorted(a,key = str.lower) # 轉換成小寫后再排序,'a'和'A'值一樣,'b'和'B'值一樣 9 ['a', 'A', 'b', 'B', 'c', 'd']
- zip:聚合傳入的每個迭代器中相同位置的元素,返回一個新的元組類型迭代器
1 >>> x = [1,2,3] #長度3 2 >>> y = [4,5,6,7,8] #長度5 3 >>> list(zip(x,y)) # 取最小長度3 4 [(1, 4), (2, 5), (3, 6)]
對象操作
- 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}
交互操作
- print:向標准輸出對象打印輸出
1 >>> print(1,2,3) 2 1 2 3 3 >>> print(1,2,3,sep = '+') 4 1+2+3 5 >>> print(1,2,3,sep = '+',end = '=?') 6 1+2+3=?
- input:讀取用戶輸入值
1 >>> s = input('please input your name:') 2 please input your name:Ain 3 >>> s 4 'Ain'
文件操作
- open:使用指定的模式和編碼打開文件,返回文件讀寫對象
1 # t為文本讀寫,b為二進制讀寫 2 >>> a = open('test.txt','rt') 3 >>> a.read() 4 'some text' 5 >>> a.close()
編譯執行
- compile:將字符串編譯為代碼或者AST對象,使之能夠通過exec語句來執行或者eval進行求值
1 >>> #流程語句使用exec 2 >>> code1 = 'for i in range(0,10): print (i)' 3 >>> compile1 = compile(code1,'','exec') 4 >>> exec (compile1) 5 0 6 1 7 2 8 3 9 4 10 5 11 6 12 7 13 8 14 9 15 16 17 >>> #簡單求值表達式用eval 18 >>> code2 = '1 + 2 + 3 + 4' 19 >>> compile2 = compile(code2,'','eval') 20 >>> eval(compile2) 21 10
- eval:執行動態表達式求值
1 >>> eval('1+2+3+4') 2 10
- exec:執行動態語句塊
-
1 >>> exec('a=1+2') #執行語句 2 >>> a 3 3
- repr:返回一個對象的字符串表現形式(給解釋器)
1 >>> a = 'some text' 2 >>> str(a) 3 'some text' 4 >>> repr(a) 5 "'some text'"
裝飾器
- 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 你好