Python自動化運維之5、內置函數


python3.x內置函數

官網詳解

 一些例子:后期慢慢接觸到再補充

# help() 詳細查看某個類有那些方法或者方法的具體使用

>>> help(str)
>>> help(str.strip)

# dir() 快速查看某個類有那些方法或者方法的具體使用

>>> dir(str)
>>> dir(str.strip)

# int() 實例化數字類型,或將其他類型轉換為數字類型,或各種進制轉換為十進制

(1)實例化數字類型
>>> i = int(23)
>>> print(type(i),i)
<class 'int'> 23

(2)將數字字符串轉換為數字類型,只能時數字字符串才能轉為數字類型,否則報錯
>>> s = "123"
>>> type(s)
<class 'str'>
>>> i = int(s)
>>> print(type(i),i)
<class 'int'> 123

(3)將二進制轉換為十進制
>>> print(int('11',base=2))
3

# float() 實例化浮點類型,或將數字字符串轉換為浮點型,僅限於數字字符串

(1) 實例化浮點類型
>>> f = float(12)
>>> print(type(f),f)
<class 'float'> 12.0

(2) 將數字字符串轉換為浮點類型
>>> s = "12"
>>> type(s)
<class 'str'>
>>> i = float(s)
>>> print(type(i),i)
<class 'float'> 12.0

# str() 實例化字符串類型,或將其他類型轉換為字符串類型

(1) 實例化字符串類型
>>> s = "python"
>>> print(type(s))
<class 'str'>

(2) 將其他類型轉換為字符串類型了
>>> s = 88888
>>> type(s)
<class 'int'>
>>> i = str(s)
>>> print(type(i),i)
<class 'str'> 88888

>>> l = [1,2,3,4,5]
>>> a = str(l)
>>> print(type(a),a)
<class 'str'> [1, 2, 3, 4, 5]
注意:列表格式或字典格式的字符串類型轉換為列表或者字典需要使用json模塊

# list() 將其他類型轉為列表類型

(1) 實例化列表類型
>>> l = list(["redhat","centos","ubuntu"])
>>> print(type(l),l)
<class 'list'> ['redhat', 'centos', 'ubuntu']

(2) 將其他類型轉換為列表
>>> s = "python"
>>> l = list(s)
>>> print(type(l),l)
<class 'list'> ['p', 'y', 't', 'h', 'o', 'n']

>>> t = ("python","I","like")
>>> l1 = list(t)
>>> print(type(l1),l1)
<class 'list'> ['python', 'I', 'like']

# tuple() 實例化元組類型,或將其他類型轉換為元組類型

(1) 實例化元組類型
>>> t1 = tuple(("redhat","centos","ubuntu","opensuse"))
>>> print(type(t1),t1)
<class 'tuple'> ('redhat', 'centos', 'ubuntu', 'opensuse')

(2) 將其他類型轉換為元組類型
>>> l = [11,22,33,44,55]
>>> type(l)
<class 'list'>
>>> t = tuple(l)
>>> print(type(t),t)
<class 'tuple'> (11, 22, 33, 44, 55)

# dict() 實例化字典,或將元組列表轉換為字典類型僅限元組形式列表類型

(1) 實例化字典類型
>>> d1 = dict({"os":"ubuntu","version":15.10,"kernel":"4.2.0-16"})
>>> print((d1),d1)
<class 'dict'> {'version': 15.1, 'os': 'ubuntu', 'kernel': '4.2.0-16'}

(2) 將元組形式的列表轉換為字典
>>> l3 = [('a',1),('b',11),('c',45)]
>>> d2 = dict(l3)
>>> print(type(d2),d2)
<class 'dict'> {'b': 11, 'c': 45, 'a': 1}

注意:zip()這個內置方法可以將兩個列表生成元組形式列表類型

# set() 實例化可變集合類型,或其他類型轉換成集合類型

(1) 實例化集合類型
>>> s = set({"fedora","geentoo","debian","centos"})
>>> print(type(s),s)
<class 'set'> {'fedora', 'centos', 'debian', 'geentoo'}

(2) 將其他類型轉換成集合set類型
>>> l = ["centos","centos","redhat","ubuntu","suse","ubuntu"]
>>> s = set(l)
>>> print(type(s),s)
<class 'set'> {'ubuntu', 'centos', 'redhat', 'suse'}

>>> d = {"kernel":"Linux","os":"ubuntu","version":"15.10"}
>>> s = set(d.keys())
>>> print(type(s),s)
<class 'set'> {'kernel', 'version', 'os'}

# frozenset() 實例化不可變集合,或類型轉換成不可變集合類型

(1) 實例化不可變集合
>>> fs = frozenset({"redhat","centos","fedora","debian","ubuntu"})
>>> print(type(fs),fs)
<class 'frozenset'> frozenset({'fedora', 'ubuntu', 'centos', 'debian', 'redhat'})

(2) 類型轉換成不可變集合
>>> l = [1,2,3,4,4,5,5]
>>> fs1 = frozenset(l)
>>> print(type(fs1),fs1)
<class 'frozenset'> frozenset({1, 2, 3, 4, 5})

# bool() 0,"",None,[],(),{}都為假,其余都為真,是int的子類

>>> bool(0)
False
>>> bool("abc")
True
>>> bool("")
False
>>> bool([])
False
>>> bool()
False
>>> issubclass(bool, int)
True

# bytes() 將字符串類型轉換成字節byte類型,在計算機底層都是以二進制存儲數據的
# 1bytes = 8bit,一個漢字utf8是用3個字節存儲,一個漢字gbk是用2個字節存儲,一個字母數字是1字節
# bytes(要轉換的字符串,按照什么編碼)

(1) 將字符串轉換為字節類型
>>> s = "大神"
>>> p = bytes(s,encoding="utf-8")
>>> print(type(p),p)
<class 'bytes'> b'\xe8\x9f\x92\xe8\x9b\x87'

(2) 將字節類型重新轉換為字符串
>>> new_s = str(p,encoding="utf-8")
>>> print(type(new_s),new_s)
<class 'str'> 大神

注意: 在文件對象處理的時候注意打開的模式如果以wb模式打開,則寫入的數據需要轉換成bytes()寫入

# bytearray() 和bytes()是一樣的,只是返回一個byte列表
# bytearray類型是一個可變的序列,並且序列中的元素的取值范圍為 [0,255]

>>> a = bytearray("大神",encoding="utf-8")
>>> print(type(a),a)
<class 'bytearray'> bytearray(b'\xe8\x9f\x92\xe8\x9b\x87')
>>> a[0]
232
>>> a[1]
159
>>> a[2]
146
>>> a[4]
155
>>> a[5]
135

# open() 是打開一個文件對象,用於對文件的操作處理

>>> with open("/etc/passwd","r") as f:
... for line in f:
...     print(line)

注意: 具體的操作,請查看文件對象這邊博客

# type() 查看某個實例屬於哪個類型
>>> s = "python"
>>> l = [1,2,3,4]
>>> t = ("linux","python")
>>> d = {"name":"linux","age":12}
>>> print(type(s),type(l),type(t),type(d))
<class 'str'> <class 'list'> <class 'tuple'> <class 'dict'>

# id() 查看對象在內存中的地址

>>> s = "python"
>>> id(s)
139639742647240
>>> l = [1,2,3,4]
>>> id(l)
139639704025736

# len() 查看實例中的長度,說白點就是元素個數
# python2.x是以字節計算,python3.x是以字符計算

>>> s = "python"
>>> len(s)
6

>>> s = "大神"
>>> len(s)
2

python3.x如果需要以字節計算,要先轉換成bytes()
>>> b = bytes(s,encoding="utf-8")
>>> len(b)
6

# input() 輸入,默認輸入的格式為字符串,輸入的數字也是字符串,需要int()轉換,python2.x是用ray_input()方法

>>> data = input("please say something:")
please say something:today is good day
>>> print(data)
today is good day

>>> data1 = input("please say something:")
please say something:123
>>> print(type(data1),data1)
<class 'str'> 123

# print() 輸出,格式化輸出
>>> name = "python"
>>> print("I love %s" % name)
I love python

注意: 具體查看格式化輸出相關博客

# all() 接收一個迭代對象
# 0,"",None,[],(),{}都為假,all是全部為真則為真,有一個假則為假

>>> s = ["python","php","java"]
>>> print(all(s))
True
>>> a = ["","python","php"]
>>> print(all(a))
False

# any() 只要有一個為真則為真,全為假則為假

>>> a = ["","python","php"]
>>> print(any(a))
True
>>> s = ["",0,(),[],{},None]
>>> print(any(s))

# max(),min(),sum() 一般是數字系列中的最大,最小,求和

>>> r = max([11,22,33])
>>> print(r)
33

>>> r1 = min([11,22,33])
>>> print(r1)
11

>>> r2 = sum([11,22,33])
>>> print(r2)
65

# abs() 求絕對值

>>> print(abs(-123))
123

# pow() 求幾次方和**是一樣的

>>> print(pow(2,10))
1024
>>> 2**10
1024

# round() 四舍五入

>>> print(round(18.8))
19
>>> print(round(18.4))
18

# divmod() 除法得余數,在分頁功能中會用到

>>> print(divmod(78,10))
(7, 8)
>>> print(divmod(45,10))
(4, 5)

# chr() ascii表的對應關系,十進制數字轉為字符
# ord() ascii表的對應關系,將ascii字符轉為數字

>>> r = chr(65)
>>> print(r)

>>> n = ord("a")
>>> print(n)

注意:利用這兩個函數和random可以實現隨機數字字母驗證碼,最后有代碼

# bin() 十進制轉二進制
# oct() 十進制轉八進制
# hex() 十進制轉十六進制

>>> print(bin(5))
>>> print(oct(9))
>>> print(hex(15))

# enumerate() 枚舉類型,實現循環的時候打印出行號,默認是0開始,也可以設置1開始

>>> li = ["redhat","centos",'fedodra']
>>> for index,data in enumerate(li):
... print(index,data)
... 
0 redhat
1 centos
2 fedodra

>>> li = ["redhat","centos",'fedodra']
>>> for index,data in enumerate(li,1):
... print(index,data)
... 
1 redhat
2 centos
3 fedodra

# sorted() 排序,不能數字和字母在一起排序和list.sorted()是一樣的,python2.x是可以混合排序的

>>> l1 = [1,5,2,55,33]
>>> a = sorted(l1)
>>> print(a)
[1, 2, 5, 33, 55]

>>> l2 = [1,5,2,55,33,66]
>>> l2.sort()
>>> print(l2)
[1, 2, 5, 33, 55, 66]

# reversed() 逆序和list.reverse()是一樣的

>>> l3 = [33,22,55,11]
>>> a = reversed(l3)
>>> print(list(a))

>>> l4 = [33,22,55,11,44]
>>> l4.reverse()
>>> print(l4)
[44, 11, 55, 22, 33]

# slice() 和字符串列表的切片的功能是一樣的

>>> s = "python"
>>> s[0:4]
'pyth'
>>> s[0:4:2]
'pt'

>>> b = slice(0,4,2)
>>> print(b)
slice(0, 4, 2)
>>> s[b]
'pt'

# zip() 取一個或多個序列為參數,把序列中的並排元素配成元組,返回元組形式的列表類型,當元素長度不同時以最短序列的長度為准

>>> l1 = ['燒餅',11,22,33]
>>> l2 = ['is',11,22,33]
>>> l3 = ['sb',11,22,33]
>>> r = zip(l1,l2,l3)
>>> print(list(r))
[('燒餅', 'is', 'sb'), (11, 11, 11), (22, 22, 22), (33, 33, 33)]

>>> temp = list(r)[0]
>>> ret = ' '.join(temp)
>>> print(ret)
燒餅 is sb

# 兩個列表合成一個字典
>>> keys = [1,2,3,4,5,6,7]
>>> vaules = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
>>> D = {}
>>> for (k,v) in zip(keys,values):
... D[k] = v
... 
>>> D
{1: 'Sun', 2: 'Mon', 3: 'Tue', 4: 'Wed', 5: 'Thu', 6: 'Fri', 7: 'Sat'}

# compile() 將代碼編譯成python代碼
# eval() 只能執行表達式,並且返回結果
# exec() 執行python代碼或者先編譯成python代碼再執行,接收:代碼或者字符串,沒有返回結果

>>> s = "print(123)"
>>> r = compile(s,"<string>","exec")
>>> exec(r)
123

# exec和eval的區別 >>> exec("7+8+9") >>> ret = eval("7+8+9") >>> print(ret) 24

# complex() 創建一個值為real + imag * j的復數或者轉化一個字符串或數為復數。如果第一個參數為字符串,則不需要指定第二個參數。
參數real: int, long, float或字符串;
參數imag: int, long, float。

>>> complex(1, 2)
(1 + 2j)
>>> complex(1) #數字
(1 + 0j)
>>> complex("1") #當做字符串處理
(1 + 0j)
>>> complex("1+2j")
(1 + 2j)
#注意:這個地方在“+”號兩邊不能有空格,也就是不能寫成"1 + 2j",應該是"1+2j",否則會報錯

# globals() 顯示所有的全局變量
# locals() 顯示所有的局部變量

>>> NAME = 'tomcat'
>>> def show():
... a = 123
... b = 456
... print(locals())
... print(globals())
... 
>>> show()

# vars() 本函數是實現返回對象object的屬性和屬性值的字典對象。如果默認不輸入參數,就打印當前調用位置的屬性和屬性值,相當於locals()的功能。如果有參數輸入,就只打印這個參數相應的屬性和屬性值。

>>> class Foo: 
... a = 1 
>>> print(vars(Foo)) 

>>> foo = Foo() 
>>> print(vars(foo))

# callable() 判斷是否可以被調用

>>> def f1():
... pass
...
>>> print(callable(f1))

>>> f2 = 123
>>> print(callable(f2))

# range() 在python2中有xrange和range,其中range會一次在內存中開辟出了所需的所有資源,而xrange則是在for循環中循環一次則開辟一次所需的內存,而在Python3中沒有xrange,只有range ,但是python3的range代表的就是xrange。range用來指定范圍,生成指定的數字。

>>> for i in range(4): 
... print(i)
... 
0
1
2
3

>>> for i in range(1,4,2): 
... print(i)
... 
1
3

# format() 格式化輸出的,和百分號是同樣的功能

>>> print("1 am {},age {}".format('jason',18)) # 用{}當作占位符
>>> print("1 am {},age {}".format(*['jason',18])) # 用*傳遞一個列表進去
>>> print("1 am {0},age {1},score{1}".format('jason',18)) # 1 am jason,age 18,score18 用 0,1等數字來應用

注意: 具體查看格式化輸出相關

# hash() 一般用在字典中的Key是進行hash計算后,值存入內存,hash值

>>> dic = {'name':'SB'}
>>> print(hash(dic['name']))

# filter() filter(函數,可迭代對象),fileter內部,循環第二個參數,將每一個元素執行第一個函數
# 如果函數返回值True,表示元素合法,就把元素存入結果ret中

>>> def f2(a):
... if a>22:
... return True

>>> li = [11,22,33,44,55]
>>> ret = filter(f2,li)
>>> print(list(ret))

注意: 對於簡單的函數用lambda可以實現
>>> result = filter(lambda a: a > 33,li)
>>> print(list(result))

# map() map(函數,可迭代的對象),循環第二個參數,將每一個元素執行第一個函數,就把返回值存入結果result中

>>> l1 = [11,22,33,44,55,66]
>>> def f3(a):
... return a + 100

>>> result = map(f3,l1)
>>> print(list(result))

注意: 對於簡單的函數用lambda可以實現
>>> result = map(lambda a: a + 100,l1)
>>> print(list(result))

# iter() 用於生成迭代器,for循環就是調用iter()生成迭代對象
# next() 用於遍歷迭代器,for循環就是調用next()實現,不過當使用next()遍歷時,迭代器沒有元素時會報錯,for則不會

>>> a = iter([1,2,3,4,5])
>>> a
<list_iterator object at 0x101402630>
>>> a.__next__()
1
>>> a.__next__()
2
>>> a.__next__()
3
>>> a.__next__()
4
>>> a.__next__()
5
>>> a.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

# hasattr() 判斷模塊中是否有某個函數名
# getattr() 獲取模塊中的函數名
# setattr() 設置模塊中的函數名
# delattr() 刪除模塊中的函數名
# __import__() 以字符串的形式導入模塊,相當於import 模塊名

# 根據URL的不同調用不同的函數處理
def run():
    inp = input("請輸入要訪問的URL:")
    mo,fn = inp.split('/')
    obj = __import__(mo)   # 以字符串的形式導入mo模塊並設置一個別名obj,相當於import mo as obj
    if hasattr(obj,fn):    # 判斷mo模塊中是否有fn函數名(函數名指向函數體)
        func = getattr(obj,fn)   # 有的話設置一個變量賦值給這個函數體
        func()                   # 執行函數
    else:
        print("網頁不存在")

run()

# isinstance() 檢查對象是不是某個類的對象,或者某個父類的對象
# issubclass() 檢查類是否是某個類的子類

class Bar:

    def __iter__(self):
        yield 1
        yield 2

class Foo(Bar):
    pass

obj = Foo()

ret1 = isinstance(obj,Foo)
print(ret1)

ret2 = isinstance(obj,Bar) # obj,Bar(obj類型和obj類型的父類) 的實例
print(ret2)

ret3 = issubclass(Foo,Bar)
print(ret3)

super() 繼承中強制使用父類中的方法

class C1:

    def f1(self): print('c1.f1') return 123 class C2(C1): def f1(self): # 主動執行父類的f1方法 ret = super(C2,self).f1() print('c2.f1') return ret obj = C2() obj.f1()

 

# property() 將函數當作屬性訪問

class Pager:

    def __init__(self,all_count):
        self.all_count = all_count

    def f1(self):
        return 123

    def f2(self,value):
        print(value)

    def  f3(self):
        print("del p.foo")

    foo = property(fget=f1,fset=f2,fdel=f3)


p = Pager(101)
result = p.foo
print(result)

p.foo = "python"

del p.foo

# staticmethod()  類中定義類方法,可以任意參數
# classmethod()   類中定義類方法,至少有一個參數cls,cls指類名,python自動傳遞

 

class Province:
    country = "中國"

    def __init__(self,name):
        self.name = name

    # 普通方法,由對象調用執行(方法屬於類),實例化才能調用
    def show(self):
        print(self.name)

    @staticmethod
    def f1(arg1,arg2):  # 可以沒有參數,或者任意參數
        # 靜態方法,由類調用執行
        print(arg1,arg2)

    @classmethod
    def f2(cls): # 至少要有cls一個參數,cls就是類名,python自動會傳,就像self
        print(cls)

Province.f1(1111,2222)
Province.f2()

 


免責聲明!

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



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