Python 函數與內置函數


1.函數的基本定義

def 函數名稱(參數)
         執行語句
         return 返回值

def : 定義函數的關鍵字;

函數名稱:顧名思義,就是函數的名字,可以用來調用函數,不能使用關鍵字來命名,做好是用這個函數的功能的英文名命名,可以采用駝峰法與下划線法;

參數:用來給函數提供數據,有形參和實參的區分;

執行語句:也叫函數體,用來進行一系列的邏輯運算;

返回值:執行完函數后,返回給調用者的數據,默認為None,所以沒有返回值時,可以不寫return。

 

2.函數的普通參數

最直接的一對一關系的參數,如:

def fun_ex(a,b):            #a,b是函數fun_ex的形式參數,也叫形參
    sum=a+b
    print('sum =',sum)
fun_ex(1,3)                  #1,3是函數fun_ex的實際參數,也叫實參

#運行結果
sum = 4

 

3.函數的默認參數

給參數定義一個默認值,如果調用函數時,沒有給指定參數,則函數使用默認參數,默認參數需要放在參數列表的最后,如:

def fun_ex(a,b=6):    #默認參數放在參數列表最后,如b=6只能在a后面
    sum=a+b
    print('sum =',sum)
fun_ex(1,3)
fun_ex(1)

#運行結果
sum = 4
sum = 7

 

4.函數的動態參數

不需要指定參數是元組或字典,函數自動把它轉換成元組或字典,如:

 1 #轉換成元組的動態參數形式,接受的參數需要是可以轉成元組的形式,就是類元組形式的數據,如數值,列表,元組。
 2 
 3 def func(*args):
 4     print(args,type(args))
 5 
 6 func(1,2,3,4,5)
 7 
 8 date_ex1=('a','b','c','d')
 9 func(*date_ex1)
10 
11 #運行結果
12 (1, 2, 3, 4, 5) <class 'tuple'>
13 ('a', 'b', 'c', 'd') <class 'tuple'>
動態參數形式一
 1 #轉換成字典的動態參數形式,接收的參數要是能轉換成字典形式的,就是類字典形式的數據,如鍵值對,字典
 2 
 3 def func(**kwargs):
 4     print(kwargs,type(kwargs))
 5 
 6 func(a=11,b=22)
 7 
 8 date_ex2={'a':111,'b':222}
 9 func(**date_ex2)
10 
11 #運行結果
12 {'b': 22, 'a': 11} <class 'dict'>
13 {'b': 222, 'a': 111} <class 'dict'>
動態參數形式二
 1 #根據傳的參數轉換成元組和字典的動態參數形式,接收的參數可以是任何形式。
 2 def func(*args,**kwargs):
 3     print(args, type(args))
 4     print(kwargs,type(kwargs))
 5 
 6 func(123,321,a=999,b=666)
 7 
 8 date_ex3={'a':123,'b':321}
 9 func(**date_ex3)
10 
11 #運行結果
12 (123, 321) <class 'tuple'>
13 {'b': 666, 'a': 999} <class 'dict'>
14 () <class 'tuple'>
15 {'b': 321, 'a': 123} <class 'dict'>
動態參數形式三

 

5.函數的返回值

運行一個函數,一般都需要從中得到某個信息,這時就需要使用return來獲取返回值,如:

def fun_ex(a,b):
    sum=a+b
    return sum      #返回sum值

re=fun_ex(1,3)   
print('sum =',re)

#運行結果
sum = 4

 

6.lambda表達式

用來表達簡單的函數,如:

#普通方法定義函數
def sum(a,b):
    return a+b
sum=sum(1,2)
print(sum)

#lambda表達式定義函數
myLambda = lambda a,b : a+b
sum=myLambda(2,3)
print(sum)

#運行結果
3
5


7.內置函數

1)內置函數列表

    Built-in Functions    
abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()  
delattr() hash() memoryview() set()  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

官方說明文檔地址:https://docs.python.org/3/library/functions.html

中文版官方說明文檔地址:http://python.usyiyi.cn/translate/python_352/index.html

2)內置函數功能

運算類內置函數:

ads(x): 取絕對值,參數是復數,返回它的模;

max(iterable, *[, key, default])/max(arg1, arg2, *args[, key]): 取所有元素的最大值;

min(iterable, *[, key, default])/min(arg1, arg2, *args[, key]): 取所有元素的最小值;

divmod(a, b): 返回a,b兩數的商和余數的一對數字(可用於分頁顯示功能);

 實例:

1 a=abs(-10)
2 b=abs(3)
3 print(a)
4 print(b)
5 
6 #運行結果
7 10
8 3
ads()
1 a=max(1,2,*(3,4))
2 b=max(*(1,2),*[5,6])
3 print(a)
4 print(b)
5 
6 #運行結果
7 4
8 6
max()
1 a=min(1,2,*(3,4))
2 b=min(*(0,1,2),*[5,6])
3 print(a)
4 print(b)
5 
6 #運行結果
7 1
8 0
min()
1 a=divmod(5,2)
2 print(a)
3 
4 #運行結果
5 (2, 1)
divmod()

 

 

類型轉換類內置函數:

int(x): 把數據轉換成整數型;

ascii(object): 類似repr(),返回一個可打印的對象字符串方式表示。當遇到非ASCII碼時,就會輸出\x\u\U等字符來表示;

bin(x): 將一個整數轉化成一個二進制字符串

class bool([x]): 根據給的數據,返回一個布爾值,TrueFalse;

class bytearray([source[, encoding[, errors]]]): 返回一個byte數組;

class bytes([source[, encoding[, errors]]]): 返回一個新的字節對象,是一個在 0<= x < 256之間的不可變的整數序列;

chr(i): 返回表示Unicode碼點為整數i的字符的字符串它是ord()的逆操作。參數的有效范圍為0到1,114,111(基址16中的0x10FFFF)。如果i超出該范圍,則會引發ValueError報錯;

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1): 將source編譯為代碼或者AST對象。代碼對象能夠通過exec語句來執行或者eval()進行求值;

class complex([real[, imag]]): 返回值形式為real + imag * j的復數,或將字符串(數字形式的字符串)或數字轉換為復數;

enumerate(iterable, start=0): 返回一個枚舉對象。iterable 必須是一個序列、一個迭代器,或者其它某種支持迭代的對象;

eval(expression, globals=None, locals=None): 還原字符串中的數據結構;

 

實例:

 1 a=3.14159
 2 b="12"
 3 c=int(a)
 4 d=int(b)
 5 print(a,type(a))
 6 print(b,type(b))
 7 print(c,type(c))
 8 print(d,type(d))
 9 
10 運行結果
11 3.14159 <class 'float'>
12 12 <class 'str'>
13 3 <class 'int'>
14 12 <class 'int'>
int()
 1 print(ascii('a'))
 2 print(ascii(999999))
 3 print(ascii('\11'))
 4 print(ascii('\200'))
 5 
 6 #運行結果
 7 'a'
 8 999999
 9 '\t'
10 '\x80'
ascii()
1 a=bin(5) 2 print(a,type(a)) 3 4 #運行結果 5 0b101 <class 'str'>
bin()
1 a=bool(5) 2 b=bool(0) 3 print(a) 4 print(b) 5 6 #運行結果 7 True 8 False
bool()
 1 #如果source為空,則返回一個長度為0的字節數組  2 a=bytearray()  3 print(a,len(a))  4  5 #如果source為字符串,則按照指定的encoding將字符串轉換為字節序列  6 b=bytearray('abcd中文','utf-8 ')  7 print(b)  8  9 #如果source為整數,則返回一個長度為source整數的初始化數組 10 c=bytearray(5) 11 print(c,len(c)) 12 13 #如果source為可迭代類型,則元素必須為[0 ,255]中的整數 14 d=bytearray([9,8,7]) 15 print(d) 16 17 #運行結果 18 bytearray(b'') 0 19 bytearray(b'abcd\xe4\xb8\xad\xe6\x96\x87') 20 bytearray(b'\x00\x00\x00\x00\x00') 5 21 bytearray(b'\t\x08\x07')
bytearray()
 1 a='abcd'
 2 b='中文'
 3 
 4 #轉換成字節編碼
 5 c=bytes(a,encoding='gbk')
 6 d=bytes(b,encoding='utf-8')
 7 e=bytes(b,encoding='gbk')
 8 
 9 #解碼過程,用什么規則編碼,就用什么解碼
10 f=d.decode('utf-8')
11 h=e.decode('gbk')
12 
13 #打印信息
14 print(c)
15 print(d)
16 print(e)
17 print(f)
18 print(h)
19 
20 #運行結果
21 '''
22 b'abcd'
23 b'\xe4\xb8\xad\xe6\x96\x87'
24 b'\xd6\xd0\xce\xc4'
25 中文
26 中文
27 '''
bytes()
 1 print(chr(65))  2 print(chr(0))  3 print(chr(33))  4 print(chr(1114111))  5  6 #運行結果  7 A  8  9 ! 10 􏿿
chr()
 1 '''  2 參數source:字符串或者AST(Abstract Syntax Trees)對象。  3  4 參數filename:代碼文件名稱,如果不是從文件讀取代碼則傳遞一些可辨認的值。  5  6 參數model:指定編譯代碼的種類。可以指定為 ‘exec’,’eval’,’single’。  7 '''  8  9 code_one = "print('hello')" 10 a = compile(code_one,'','exec') 11 exec(a) 12 13 code_two ="print(1+2*3)" 14 b = compile(code_two,'','eval') 15 eval(b) 16 print(b) 17 18 #運行結果 19 hello 20 7 21 <code object <module> at 0x005419D0, file "", line 1>
compile()
 1 print(complex(1,2))  2  3 #如果省略imag,則默認為零,構造函數會像int和float一樣進行轉換。如果省略這兩個參數,則返回0j。  4 print(complex(1))  5  6 #如果第一個參數為字符串,則不需要指定第二個參數。  7 print(complex('1'))  8  9 #當從字符串轉化成復數的時候,字符串中+或者-兩邊不能有空白,如下不能寫成"1 + 2j",應該是"1+2j",否則會報錯 10 print(complex('1+2j')) 11 12 #運行結果 13 (1+2j) 14 (1+0j) 15 (1+0j) 16 (1+2j)
complex()
1 str='abcd'     
2 print(list(enumerate(str)))
3 print(dict(enumerate(str)))
4 
5 #運行結果
6 [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
7 {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
enumerate()
 1 x=1
 2 print(eval('x+1'))
 3 
 4 dic={'a':1,'b':2}
 5 str=str(dic)
 6 print(str,type(str))
 7 ev=eval(str)
 8 print(ev,type(ev))
 9 
10 #運行結果
11 2
12 {'a': 1, 'b': 2} <class 'str'>
13 {'a': 1, 'b': 2} <class 'dict'>
eval()

 

 判斷類內置函數:

all(iterable): 判斷iterable序列中是否所有元素都為真,或整個序列為空,滿足條件則返回True;

any(iterable): 判斷iterable序列中是否任意一個元素為真,滿足條件則返回True,這里整個序列為空,返回False;

callable(object): 判斷對象object是否可調用。如果返回True,object仍然可能調用失敗;但如果返回False,調用對象ojbect絕對不會成功;

實例:

 1 a=[]
 2 b=[1,2,'']
 3 c=[0,1,2,3]
 4 d=[1,2,3]
 5 print(all(a))
 6 print(all(b))
 7 print(all(c))
 8 print(all(d))
 9 
10 #運行結果
11 True
12 False
13 False
14 True
all()
 1 a=[]
 2 b=[1,2,'']
 3 c=[0,0,0,1]
 4 d=[0,0,0]
 5 print(any(a))
 6 print(any(b))
 7 print(any(c))
 8 print(any(d))
 9 
10 #運行結果
11 False
12 True
13 True
14 False
any()
 1 #基本數據類型callable情況
 2 print('基本數據類型callable情況')
 3 print(callable(1))
 4 print(callable('string'))
 5 
 6 #函數的callable情況
 7 print('#函數的callable情況')
 8 def sum(a,b):
 9     return a+b
10 a=sum(1,2)
11 print(callable(sum))
12 print(callable(a))
13 
14 #類的callable情況
15 print('#類的callable情況')
16 class ex_1:
17     def add(self):
18         return 0
19 b=ex_1()
20 print(callable(ex_1))
21 print(callable(b))
22 class ex_2:
23     def __call__(self, *args, **kwargs):
24         return 0
25 c=ex_2()
26 print(callable(ex_2))
27 print(callable(c))    #類是可調用的,而類的實例實現了__call__()方法才可調用。
28 
29 #運行結果
30 '''
31 基本數據類型callable情況
32 False
33 False
34 #函數的callable情況
35 True
36 False
37 #類的callable情況
38 True
39 False
40 True
41 True
42 '''
callable()

 

IO操作類內置函數:

input([prompt]): 獲取用戶的輸入,獲取的數據會轉換成字符串;

 實例:

 1 a=input('fist input  :')
 2 b=input('second input :')
 3 print(a,type(a))
 4 print(b,type(b))
 5 
 6 #運行結果
 7 fist input  :as
 8 second input :12
 9 as <class 'str'>
10 12 <class 'str'>
input()

 

基礎數據類型內置函數:

class dict(): 創建字典。

 

 

其他內置函數:

help([object]): 調用內置幫助系統;

classmethod(function): 用來指定一個類的方法為類方法,沒有此參數指定的類的方法為實例方法,類方法既可以直接類調用(C.f()),也可以進行實例調用(C().f());

delattr(object, name): 刪除object對象的某個屬性;

dir([object]): 顯示函數內置屬性和方法;

 實例:

  1 help(int)
  2 
  3 #運行結果
  4 Help on class int in module builtins:
  5 
  6 class int(object)
  7  |  int(x=0) -> integer
  8  |  int(x, base=10) -> integer
  9  |  
 10  |  Convert a number or string to an integer, or return 0 if no arguments
 11  |  are given.  If x is a number, return x.__int__().  For floating point
 12  |  numbers, this truncates towards zero.
 13  |  
 14  |  If x is not a number or if base is given, then x must be a string,
 15  |  bytes, or bytearray instance representing an integer literal in the
 16  |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 17  |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 18  |  Base 0 means to interpret the base from the string as an integer literal.
 19  |  >>> int('0b100', base=0)
 20  |  4
 21  |  
 22  |  Methods defined here:
 23  |  
 24  |  __abs__(self, /)
 25  |      abs(self)
 26  |  
 27  |  __add__(self, value, /)
 28  |      Return self+value.
 29  |  
 30  |  __and__(self, value, /)
 31  |      Return self&value.
 32  |  
 33  |  __bool__(self, /)
 34  |      self != 0
 35  |  
 36  |  __ceil__(...)
 37  |      Ceiling of an Integral returns itself.
 38  |  
 39  |  __divmod__(self, value, /)
 40  |      Return divmod(self, value).
 41  |  
 42  |  __eq__(self, value, /)
 43  |      Return self==value.
 44  |  
 45  |  __float__(self, /)
 46  |      float(self)
 47  |  
 48  |  __floor__(...)
 49  |      Flooring an Integral returns itself.
 50  |  
 51  |  __floordiv__(self, value, /)
 52  |      Return self//value.
 53  |  
 54  |  __format__(...)
 55  |      default object formatter
 56  |  
 57  |  __ge__(self, value, /)
 58  |      Return self>=value.
 59  |  
 60  |  __getattribute__(self, name, /)
 61  |      Return getattr(self, name).
 62  |  
 63  |  __getnewargs__(...)
 64  |  
 65  |  __gt__(self, value, /)
 66  |      Return self>value.
 67  |  
 68  |  __hash__(self, /)
 69  |      Return hash(self).
 70  |  
 71  |  __index__(self, /)
 72  |      Return self converted to an integer, if self is suitable for use as an index into a list.
 73  |  
 74  |  __int__(self, /)
 75  |      int(self)
 76  |  
 77  |  __invert__(self, /)
 78  |      ~self
 79  |  
 80  |  __le__(self, value, /)
 81  |      Return self<=value.
 82  |  
 83  |  __lshift__(self, value, /)
 84  |      Return self<<value.
 85  |  
 86  |  __lt__(self, value, /)
 87  |      Return self<value.
 88  |  
 89  |  __mod__(self, value, /)
 90  |      Return self%value.
 91  |  
 92  |  __mul__(self, value, /)
 93  |      Return self*value.
 94  |  
 95  |  __ne__(self, value, /)
 96  |      Return self!=value.
 97  |  
 98  |  __neg__(self, /)
 99  |      -self
100  |  
101  |  __new__(*args, **kwargs) from builtins.type
102  |      Create and return a new object.  See help(type) for accurate signature.
103  |  
104  |  __or__(self, value, /)
105  |      Return self|value.
106  |  
107  |  __pos__(self, /)
108  |      +self
109  |  
110  |  __pow__(self, value, mod=None, /)
111  |      Return pow(self, value, mod).
112  |  
113  |  __radd__(self, value, /)
114  |      Return value+self.
115  |  
116  |  __rand__(self, value, /)
117  |      Return value&self.
118  |  
119  |  __rdivmod__(self, value, /)
120  |      Return divmod(value, self).
121  |  
122  |  __repr__(self, /)
123  |      Return repr(self).
124  |  
125  |  __rfloordiv__(self, value, /)
126  |      Return value//self.
127  |  
128  |  __rlshift__(self, value, /)
129  |      Return value<<self.
130  |  
131  |  __rmod__(self, value, /)
132  |      Return value%self.
133  |  
134  |  __rmul__(self, value, /)
135  |      Return value*self.
136  |  
137  |  __ror__(self, value, /)
138  |      Return value|self.
139  |  
140  |  __round__(...)
141  |      Rounding an Integral returns itself.
142  |      Rounding with an ndigits argument also returns an integer.
143  |  
144  |  __rpow__(self, value, mod=None, /)
145  |      Return pow(value, self, mod).
146  |  
147  |  __rrshift__(self, value, /)
148  |      Return value>>self.
149  |  
150  |  __rshift__(self, value, /)
151  |      Return self>>value.
152  |  
153  |  __rsub__(self, value, /)
154  |      Return value-self.
155  |  
156  |  __rtruediv__(self, value, /)
157  |      Return value/self.
158  |  
159  |  __rxor__(self, value, /)
160  |      Return value^self.
161  |  
162  |  __sizeof__(...)
163  |      Returns size in memory, in bytes
164  |  
165  |  __str__(self, /)
166  |      Return str(self).
167  |  
168  |  __sub__(self, value, /)
169  |      Return self-value.
170  |  
171  |  __truediv__(self, value, /)
172  |      Return self/value.
173  |  
174  |  __trunc__(...)
175  |      Truncating an Integral returns itself.
176  |  
177  |  __xor__(self, value, /)
178  |      Return self^value.
179  |  
180  |  bit_length(...)
181  |      int.bit_length() -> int
182  |      
183  |      Number of bits necessary to represent self in binary.
184  |      >>> bin(37)
185  |      '0b100101'
186  |      >>> (37).bit_length()
187  |      6
188  |  
189  |  conjugate(...)
190  |      Returns self, the complex conjugate of any int.
191  |  
192  |  from_bytes(...) from builtins.type
193  |      int.from_bytes(bytes, byteorder, *, signed=False) -> int
194  |      
195  |      Return the integer represented by the given array of bytes.
196  |      
197  |      The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
198  |      
199  |      The byteorder argument determines the byte order used to represent the
200  |      integer.  If byteorder is 'big', the most significant byte is at the
201  |      beginning of the byte array.  If byteorder is 'little', the most
202  |      significant byte is at the end of the byte array.  To request the native
203  |      byte order of the host system, use `sys.byteorder' as the byte order value.
204  |      
205  |      The signed keyword-only argument indicates whether two's complement is
206  |      used to represent the integer.
207  |  
208  |  to_bytes(...)
209  |      int.to_bytes(length, byteorder, *, signed=False) -> bytes
210  |      
211  |      Return an array of bytes representing an integer.
212  |      
213  |      The integer is represented using length bytes.  An OverflowError is
214  |      raised if the integer is not representable with the given number of
215  |      bytes.
216  |      
217  |      The byteorder argument determines the byte order used to represent the
218  |      integer.  If byteorder is 'big', the most significant byte is at the
219  |      beginning of the byte array.  If byteorder is 'little', the most
220  |      significant byte is at the end of the byte array.  To request the native
221  |      byte order of the host system, use `sys.byteorder' as the byte order value.
222  |      
223  |      The signed keyword-only argument determines whether two's complement is
224  |      used to represent the integer.  If signed is False and a negative integer
225  |      is given, an OverflowError is raised.
226  |  
227  |  ----------------------------------------------------------------------
228  |  Data descriptors defined here:
229  |  
230  |  denominator
231  |      the denominator of a rational number in lowest terms
232  |  
233  |  imag
234  |      the imaginary part of a complex number
235  |  
236  |  numerator
237  |      the numerator of a rational number in lowest terms
238  |  
239  |  real
240  |      the real part of a complex number
help()
 1 class C:
 2     @classmethod
 3     def f(self):
 4         print('this is class method')
 5 print(C.f())
 6 print(C().f())
 7 
 8 class D:
 9     def f(self):
10         print('this is not a class method')
11 print(D().f())            #這里不能用D.f()
12 
13 #運行結果
14 this is class method
15 None
16 this is class method
17 None
18 this is not a class method
19 None
classmethod()
 1 class Dog :
 2     def __init__(self,name,age):
 3         self.name=name
 4         self.age=age
 5 dahuang = Dog('dahuang',2)
 6 print(dir(dahuang))
 7 delattr(dahuang,"age")
 8 print(dir(dahuang))
 9 
10 #運行結果
11 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name']
12 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']
delattr()
1 print(dir(int))
2 
3 #運行結果
4 ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__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__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
dir()

 


免責聲明!

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



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