日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python學習之內置函數總結_python

作者:渴望力量的哈士奇 ? 更新時間: 2022-06-01 編程語言

前面的一些章節我們學習了 python 的一些常用的 內置包、內置模塊 與 第三方包、第三方模塊。今天的章節我們來總結一下 python 中常用的 內置函數,這里可能包括我們之前學習過的和未學習過的。我們一同進行一下簡單的介紹。

常用函數

函數名 參數 介紹 返回值 示例
abs number 返回數字的絕對值 正數字 abs(-1)
all list 判斷列表內容是否全是 true bool all([0, ‘123’])
help object 打印對象的用法 help(list)
enumerate iterable 幫助我們在for循環,迭代時顯示索引 for index, item in enumerate(list)
input str 命令行輸入消息 str input(‘請輸入信息:’)
isinstance object,type 判斷對象是否是某種類型 bool input(‘請輸入信息:’)
type object 判斷對象的類型 str type(‘test’)
vars instance 返回實例化的字典信息 dict ?
dir object 返回對象中所有可用的方法和屬性 list dir(‘asd’)
hasattr object, key 判斷對象中,是否有某個屬性 bool hasattr(‘1’, upper)
setattr obj,key,value 為實例化對象添加屬性與值 setattr(instance, ‘run’, ‘go’)
getattr object, key 通過對象獲取屬性 任何類型 getattr(obj, key)
any iterable 判斷內容是否有 true 值 bool any([1, 0, ‘’])

接下來我們看一看 在 ipython 終端 演示的這些函數的示例。

abs 函數 演示

In [1]: abs(-6)
Out[1]: 6

In [2]: abs(0)
Out[2]: 0

In [3]: abs(6.6)
Out[3]: 6.6

all 函數 演示

In [4]: result = all(['P' in 'Python', True, None])

In [5]: print(result)
# >>> 執行結果為 :False

In [6]: result = all([True, 'test', 10, len('python')])

In [7]: print(result)
# >>> 執行結果為 :True

enumerate 函數 演示

In [8]: books = ['爬蟲從入門到入獄', '面向監欲編程', '數據庫開發從刪庫到跑路']

In [9]: for index, item in enumerate(books):
   ...:     print(index, item)
   ...: 

# >>> 執行結果如下:
# >>> 0 爬蟲從入門到入獄
# >>> 1 面向監欲編程
# >>> 2 數據庫開發從刪庫到跑路

input 函數 演示

1.模擬輸入用戶名和密碼

2.打印輸出用戶名和密碼

3.打印輸出密碼的長度和類型

username = input("請輸入用戶名:")
password = input("請輸入密碼:")


if __name__ == '__main__':
    print("用戶名為:" + username)
    print("密碼為:" + password)
    print("密碼長度為:" + str(len(password)))
    print("密碼的類型為:" + str(type(password)))

輸出結果如下圖:

isinstance 函數 演示

In [10]: name = 'Neo'

In [11]: isinstance(name, str)
Out[11]: True

In [12]: isinstance(name, int)
Out[12]: False

vars 函數 演示

描述:

vars() 函數返回對象object的屬性和屬性值的字典對象。

語法

vars() 函數語法:vars([object])

參數

object – 對象

返回值

返回對象object的屬性和屬性值的字典對象,如果沒有參數,就打印當前調用位置的屬性和屬性值 類似 locals()。

實例:

class Test(object):
    def __init__(self):
        self.a = 1
        self.b = 2
 
    def to_vars(self):
        return vars(self)
 
 
 
test = Test()
print test.to_vars()

hasattr 函數 演示

hasattr() 函數用于判斷對象是否包含對應的屬性。

hasattr(object, name)

object – 對象。

name – 字符串,屬性名。

return

如果對象有該屬性返回 True,否則返回 False。

實例:

class variable:
    x = 1
    y = 'a'
    z = True

test = variable() 

print(hasattr(test, 'x'))
print(hasattr(test, 'y'))
print(hasattr(test, 'z'))
print(hasattr(test, 'no'))

# >>> 執行結果如下:
# >>> True
# >>> True
# >>> True
# >>> False

setattr 函數 演示

給對象的屬性賦值,若屬性不存在,先創建再賦值。

語法格式如下:

setattr(object,name,value)

object:理解為對象,也就是要設置的對象

name:理解為名字,也就是要設置的屬性名(字符串格式喲!)

value:理解為值,也就是要設置的屬性值

class function_demo():
    name = 'demo'
    def run(self):
        return "hello function"


functiondemo = function_demo()
res = hasattr(functiondemo, 'age')  # 判斷age屬性是否存在,False
print(res)

setattr(functiondemo, 'age', 18 )  #對age屬性進行賦值,無返回值

res1 = hasattr(functiondemo, 'age') #再次判斷屬性是否存在,True
print(res1)

# >>> 執行結果如下:
# >>> False
# >>> True

注意:setattr 與 hasattr 函數,這兩者本身就是一個函數,set顧名思義就是設置的意思,而has就是檢測是否存在的意思.

getattr 函數 演示

獲取對象object的屬性或者方法,如果存在則打印出來,如果不存在,打印默認值,默認值可選。

注意:如果返回的是對象的方法,則打印結果是:方法的內存地址,如果需要運行這個方法,可以在后面添加括號()

class function_demo():
    name = 'neo'
    def run(self):
        return "neo like run"


functiondemo = function_demo()
getattr(functiondemo, 'name')	# 獲取name屬性,存在就打印出來--- neo

getattr(functiondemo, "run")	# 獲取run方法,存在打印出 方法的內存地址

getattr(functiondemo, "age", 18)	# 獲取不存在的屬性,返回一個默認值;這里的默認值為 '18'

getattr(functiondemo, "age")	# 獲取不存在的屬性,則會報錯,如下圖:

執行結果示意如下圖:

any 函數 演示

any 函數用于判斷給定的可迭代參數 iterable 是否全部為 False ,則返回 False,如果有一個為 True,則返回 True。

元素除了是 0、空、False 外都算 True。

函數等價于:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

語法:any(iterable)

示例如下,輔助理解:

>>> a = [0, False, [], {}, ()]
>>> b = [0, False, [], {}, (), [[]]]
>>> c = {}
>>> any(a)
False
>>> any(b) # b 中的元素 [[]] 為 True 。
True
>>> any(c)
False

原文鏈接:https://blog.csdn.net/weixin_42250835/article/details/123835236

欄目分類
最近更新