1. <nobr id="easjo"><address id="easjo"></address></nobr>

      <track id="easjo"><source id="easjo"></source></track>
      1. 
        

      2. <bdo id="easjo"><optgroup id="easjo"></optgroup></bdo>
      3. <track id="easjo"><source id="easjo"><em id="easjo"></em></source></track><option id="easjo"><span id="easjo"><em id="easjo"></em></span></option>
          貴州做網站公司
          貴州做網站公司~專業!靠譜!
          10年網站模板開發經驗,熟悉國內外開源網站程序,包括DEDECMS,WordPress,ZBlog,Discuz! 等網站程序,可為您提供網站建設,網站克隆,仿站,網頁設計,網站制作,網站推廣優化等服務。我們專注高端營銷型網站,企業官網,集團官網,自適應網站,手機網站,網絡營銷,網站優化,網站服務器環境搭建以及托管運維等。為客戶提供一站式網站解決方案?。?!

          Python核心編程

          來源:互聯網轉載 時間:2024-01-29 08:07:40

          數據類型

          基本數據類型:
          整型(int),浮點型(float),字符串(str),列表(list),元組(tuple),字典(dict),集合(set),布爾(bool)

          數值類型(整數,浮點,布爾)
          序列類型(字符串,列表,元組)
          散列類型(字典,集合)

          字節類型 a=bytes(‘123’)/a=b’123’
          字節數組bytearrary(‘123’)

          可變序列:列表,集合,字典
          不可變序列:字符串,元組

          數據類型方法

          —字符串方法

          增:
          字符串拼接
          1.str1+str2+str3
          2.””.join([str1,str2,str3])
          3."%s %s %s"%(str1,str2,str3)
          4."{} {} {}".format(str1,str2,str3)

          刪:
          x.replace(m,n,x) m:準備替換的內容 n:替換的內容 x:替換的個數

          查:
          x.index(m) m:索引的內容
          x.find(m) m:索引的內容
          x.count(m) m:計數的內容
          x.isdigit() x是否是數字
          x.isalpha() x是否是字母
          x.isupper() x是否是大寫
          x.islower() x是否是小寫
          x.startswith(m) x是否以m開頭
          x.endswith(m) x是否以m結尾

          改:
          x.upper() x轉化為大寫
          x.lower() x轉化為小寫
          x.strip()去x左右空白/lstrip去左空白/rstrip去右空白
          x.title() x標題化
          x.capitalize() x第一個字母大寫
          x.split(m,x) 以m為界分割 分割x次

          —列表方法

          增:
          li.append(m) m:添加的內容
          li.insert(x,m) x:元素下標位置 m:插入的內容
          li.extend(list) list:為另一個列表

          刪:
          li.pop(x) x:刪除一個元素并返回該元素的值 若無參數x則從最后開始刪除
          li.remove(m) m:需要刪除的內容
          li.clear() 清空列表li

          查:
          li.index(m) m:索引的內容
          li.count(m) m:計數的內容

          改:
          list[n]=x

          其他:
          copy() 淺復制
          import copy 深復制 適用于兩層列表
          list1=copy.deepcopy(list2)
          永久排序
          li.sort(reverse=True/False) m:列表 True倒排序 False正排序
          m.reverse() 永久倒排序
          臨時排序
          sorted(li,reverse=True/False) m:列表 True倒排序 False正排序
          reversed(m) 臨時倒排序

          —元組方法

          查:
          t.index(m) m:索引的內容
          t.count(m) m:計數的內容

          —集合方法

          交集& 并集| 差集-

          增:
          a.add(m) m:向集合里面添加的內容
          刪:
          a.pop() 隨機刪除集合內容
          a.remove() 指定刪除集合內容
          查:
          a.isdisjoint(b) a與b是否存在交集
          a.issubset(b) a是b的子集嗎
          a.issuperset(b) a是b的父集嗎
          改:
          a.update(m) 向集合里面添加元素m可以為字符串 列表 元組 集合 字典

          —字典方法

          增:
          d=dict.fromkeys(m,n) m:鍵的來源可迭代對象 n:設置值的默認值
          d.setdefault(m,n) 查詢有則返回無則添加m:鍵 n:值

          刪:
          d.clear() 清空字典
          d.pop(m) m:鍵 刪除以m為鍵的字典
          d.popitem() 刪除最后一個字典

          改:
          d.update(m) m:添加的字典
          dic[m]=n m:鍵 n:值

          查:
          d.get(m) m:鍵 返回m鍵對應的值
          d.keys() 獲得鍵的列表
          d.values() 獲得值的列表
          d.items() 同時獲得鍵與值的元組 再通過遍歷獲得鍵與值

          判斷類型:type() isinstance(變量,類型)

          運算符及其優先級

          運算符說明
          ** ^ !指數 按位翻轉 非
          * / % //乘 除 取模 整除
          + -加 減
          >> <<右移 左移
          == >= <= > < !=是否 /等于 大于等于 小于等于 大于 小于 不等于
          = += -= *= /= %= **= //=賦值
          is is not判斷內存地址是否相同
          in not in判斷成員是否存在
          and or not與 或 非
          流程控制

          if-else
          語法:

          if 條件:
          語句
          else:
          語句
          1
          2
          3
          4
          例子:

          a=1
          #使用方式一
          if a>1:
          print('大于1')
          else:
          print('小于等于1')
          #使用方式二
          print('大于1') if a>1 else print('小于等于1')
          輸出:
          >>小于等于1
          >>小于等于1
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          if-elif-else
          語法:

          if 條件:
          語句
          elif 條件:
          語句
          else:
          語句
          1
          2
          3
          4
          5
          6
          例子:

          a=1
          if a>1:
          print('大于1')
          elif a<1:
          print('小于1')
          else:
          print('等于1')
          輸出:
          >>等于1
          1
          2
          3
          4
          5
          6
          7
          8
          9
          while
          語法:

          while 條件:
          語句
          1
          2
          例子:

          a=5
          while a>0:
          print(a)
          a-=1
          輸出:
          >>5
          >>4
          >>3
          >>2
          >>1
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          while-else
          語法:

          while 條件:
          語句
          else:
          循環結束后執行的語句
          1
          2
          3
          4
          例子:

          a=5
          while a>0:
          print(a)
          a-=1
          #循環中若出現break則跳出循環,且不再執行else中的語句
          else:
          print('ok')
          輸出:
          >>5
          >>4
          >>3
          >>2
          >>1
          >>ok
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          for循環

          for i in 可迭代對象:
          語句
          1
          2
          例子:實現九九乘法表

          for i in range(1,10):
          for j in range(1,i+1):
          print(str(i)+'x'+str(j)+'='+str(i*j),end=' ')
          print('\n',end='')
          輸出:
          >>1x1=1
          >>2x1=2 2x2=4
          >>3x1=3 3x2=6 3x3=9
          >>4x1=4 4x2=8 4x3=12 4x4=16
          >>5x1=5 5x2=10 5x3=15 5x4=20 5x5=25
          >>6x1=6 6x2=12 6x3=18 6x4=24 6x5=30 6x6=36
          >>7x1=7 7x2=14 7x3=21 7x4=28 7x5=35 7x6=42 7x7=49
          >>8x1=8 8x2=16 8x3=24 8x4=32 8x5=40 8x6=48 8x7=56 8x8=64
          >>9x1=9 9x2=18 9x3=27 9x4=36 9x5=45 9x6=54 9x7=63 9x8=72 9x9=81
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          函數

          —函數的定義

          定義函數

          def myfunc(x):
          if x >= 0:
          return x
          else:
          return -x
          1
          2
          3
          4
          5
          空函數

          def emptyfunc():
          pass
          1
          2
          參數檢查

          def checkfunc(x):
          if not isinstance(x,(int,float)):
          raise TypeError("must be int or float type!")
          if x >= 0:
          return x
          else:
          return -x
          1
          2
          3
          4
          5
          6
          7
          返回多個值

          def price(x):
          apple=x*2
          banana=x*2.5
          return apple,banana
          a,b=price(1)
          1
          2
          3
          4
          5
          函數返回多值其實就是返回一個元組
          —函數的參數

          必選參數parameter

          def printdetail1(name,age,telephone):
          print("姓名:",name)
          print("年齡:",age)
          print("電話:",telephone)
          printdetail1("Jack",12,12356435678)
          1
          2
          3
          4
          5
          默認參數parameter=value

          def printdetail2(name,age,telephone,gender='fale'):
          print("姓名:",name)
          print("性別:",gender)
          print("年齡:",age)
          print("電話:",telephone)
          printdetail2("Jack",12,12356435678,gender='female')
          1
          2
          3
          4
          5
          6
          可變參數*
          1.不定長傳參

          def fun1(*number):
          for i in number:
          print(i)
          fun1(1,2,3,4,5,6,7,8)
          1
          2
          3
          4
          2.元組和列表的壓包

          def fun2(*number):
          s=0
          for i in number:
          s+=i
          print(s)
          fun2(*[1,2,3,4,5])
          fun2(*(1,2,3,4,5))
          1
          2
          3
          4
          5
          6
          7
          關鍵參數**
          使用方法一

          def fun(id,name,**kargs):
          print("id:",id)
          print("name:",name)
          print("others:",kargs)
          fun(2,"xiaohua",sex="man",age='12')
          1
          2
          3
          4
          5
          使用方法二

          extra={'sex': 'man', 'age': 12}
          def fun(id,name,**kargs):
          print("id:",id)
          print("name:",name)
          print("others:",kargs)
          fun(2,"xiaohua",sex=extra['sex'],age=extra['age'])
          1
          2
          3
          4
          5
          6
          使用方法三

          extra={'sex': 'man', 'age': 12}
          def fun(id,name,**kargs):
          print("id:",id)
          print("name:",name)
          print("others:",kargs)
          fun(2,"xiaohua",**extra)
          1
          2
          3
          4
          5
          6
          關鍵字參數*

          def fun(name,age,*,city,job,completion):
          print("name:",name)
          print("age:",age)
          print("city:",city)
          print("job:",job)
          print("completion:",completion)
          fun('Jack',12,city='shanghai',job='teacher',completion=True)
          1
          2
          3
          4
          5
          6
          7
          命名關鍵字參數需要一個特殊分隔符*,后面的參數被視為命名關鍵字參數
          如果函數定義中已經有了一個可變參數,后面跟著的命名關鍵字參數就不再需要一個特殊分隔符*了
          參數組合

          def fun(parameter,*args,keyparameter,**kargs):
          print(parameter)
          print(args)
          print(keyparameter)
          print(kargs)
          fun(1,*(1,2,3,4),keyparameter=True,**{'id':2})
          1
          2
          3
          4
          5
          6
          參數定義的順序必須是:必選參數、默認參數、可變參數、命名關鍵字參數和關鍵字參數
          —函數的遞歸

          #階乘計算
          def fact(n):
          if n == 1:
          return 1
          return n * fact(n-1)
          1
          2
          3
          4
          5
          必須設置函數終止條件
          使用遞歸函數的優點是邏輯簡單清晰,缺點是過深的調用會導致棧溢出。
          函數作用域
          1.外部不能訪問函數內部變量
          2.函數內部能夠訪問函數外部變量
          3.函數里面不能修改函數外部變量(若要修改需聲明global x x=n)
          4.函數里面和函數外部變量名相同

          函數式編程

          —高階函數

          map()
          map(函數名,列表/元組/集合/字符串)

          a='12345'
          def square(x):
          return int(x)*int(x)

          b=list(map(square,a))
          print(b)
          輸出:
          >>[1, 4, 9, 16, 25]
          1
          2
          3
          4
          5
          6
          7
          8
          map()把傳入的函數依次作用于每個元素,處理完后返回的是生成器類型,需要用list生成數據
          filter()
          filter(函數名,列表/元組/集合/字符串)

          a=[1,2,3,4,5,6,7,8,9,10]
          def even_number(x):#篩選偶數
          return x%2==0
          b=list(filter(even_number,a))

          print(b)
          輸出:
          >>[2, 4, 6, 8, 10]
          1
          2
          3
          4
          5
          6
          7
          8
          a=['A', '', 'B', None, 'C', ' ']
          def remove_blank(x):#去除空元素
          return x and x.strip()

          b=list(filter(remove_blank,a))
          print(b)
          輸出:
          >>['A', 'B', 'C']
          1
          2
          3
          4
          5
          6
          7
          8
          filter()把傳入的函數依次作用于每個元素,然后根據返回值是True還是False決定保留還是丟棄該元素,處理完后返回的是生成器類型,需要用list生成數據
          —返回函數

          def delay_sum(*args):
          def sumfunc():
          s=0
          for i in args:
          s+=i
          return s
          return sumfunc
          f=delay_sum(1,2,3,4)
          print(f())
          輸出:
          >>10
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          —函數的閉包

          def count():
          fs = []
          for i in range(1, 4):
          def f():
          return i*i
          fs.append(f)
          return fs

          f1, f2, f3 = count()
          print(f1())
          print(f2())
          print(f3())
          輸出:
          >>9
          >>9
          >>9
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          def count():
          def f(j):
          def g():
          return j*j
          return g
          fs = []
          for i in range(1, 4):
          fs.append(f(i)) # f(i)立刻被執行,因此i的當前值被傳入f()
          return fs
          f1,f2,f3=count()
          print(f1())
          print(f2())
          print(f3())
          輸出:
          >>1
          >>4
          >>9
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          —匿名函數

          lambda 形參:含形參的表達式

          f = lambda x:x+1
          print(list(map(f,[1,2,3,4,5])))
          輸出:
          >>[2, 3, 4, 5, 6]
          1
          2
          3
          4
          lambda返回的是函數地址
          lambda常與map函數聯用
          —裝飾器

          裝飾器:我們要增強函數的功能,比如,在函數調用前后自動打印日志,但又不希望修改函數的定義,這種在代碼運行期間動態增加功能的方式,稱之為“裝飾器”(Decorator)
          定義裝飾器

          def decorator(func):
          def wrapper(*args,**kargs):#可以自行定義傳入的
          print(func,__name__)
          return func(*args,**kargs)
          return wrapper
          1
          2
          3
          4
          5
          使用裝飾器

          #使用方法一
          now=decorator(函數名)#裝飾器不傳入參數時
          now=decorator(參數)(函數名)#裝飾器傳入參數時
          now()#執行被裝飾過的函數

          #使用方法二
          @decorator#已定義的裝飾器
          def f():#自定義函數
          pass
          f()#執行被裝飾過的函數
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          自身不傳入參數的裝飾器

          def login(func):
          def wrapper(*args,**kargs):
          print('函數名:%s'% func.__name__)
          return func(*args,**kargs)
          return wrapper
          @login
          def f():
          print('inside decorator!')
          f()
          輸出:
          >>函數名:f
          >>函數本身:inside decorator!
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          自身傳入參數的裝飾器

          def login(text):
          def decorator(func):
          def wrapper(*args,**kargs):
          print('%s----%s'%(text,func.__name__))
          return func(*args,**kargs)
          return wrapper
          return decorator

          @login('this is a parameter of decorator')
          def f():
          print('2019-06-13')
          f()
          輸出:
          >>this is a parameter of decorator----f
          >>2019-06-13
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          內置裝飾器
          @property:就像訪問屬性一樣和普通訪問少了一個()
          @staticmethod: 靜態方法和class類斷開聯系 既可以先實例化再調用也可以直接調
          @classmethod: 類方法 接調用調用函數Rectangle.func()

          class Rectangle:
          def __init__(self, length, width):
          self.length = length
          self.width = width

          @property # 就像訪問屬性一樣和普通訪問少了一個()
          def area(self):
          return self.width * self.length


          @staticmethod # 靜態方法和class類斷開聯系 既可以先實例化再調用也可以直接調用
          def func():
          print('staticmethod func')

          @classmethod # 類方法 接調用調用函數Rectangle.func()
          def show(cls): # cls代表類本身
          print(cls)
          a=Rectangle(12,12)

          # 就像訪問屬性一樣和普通訪問少了一個()
          print(a.area)

          # 靜態方法和class類斷開聯系 既可以先實例化再調用也可以直接調用
          a.func()
          Rectangle.func()

          # 類方法
          Rectangle.show()
          輸出:
          >>144
          >>>staticmethod func
          >>staticmethod func
          >><class '__main__.Rectangle'>
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          28
          29
          30
          31
          32
          33
          —內置函數

          常用函數
          len()求長度
          min()求最小值
          max()求最大值
          sorted()排序
          sum()求和
          進制轉換函數
          bin()轉換為二進制
          oct()轉換為八進制
          hex()轉換為十六進制
          ord()字符轉ASCII碼
          chr()ASCII碼轉字符

          內置對象查看:dir(_builtins_)

          —高級內置函數

          enumerate() 轉化為元組標號
          eval(str)只能運行一行字符串代碼
          exec(str)執行字符串編譯過的字符串 可以運行多行字符串代碼
          filter(函數名,可迭代對象)過濾器
          map(函數名,可迭代對象)對每個可迭代對象的每個元素處理
          zip(可迭代對象,可迭代對象)將對象逐一配對

          高級特性

          —切片

          字符串的切片

          s='hello world!'
          print(s[0])#取0對應的下標值
          print(s[::])#取全部值
          print(s[::2])#步長為2
          print(s[1:5])#左開右閉區間
          print(s[1:])#包含下標為1對應的值
          print(s[:5])#不包含下標為5對應的值
          輸出:
          >>h
          >>hello world!
          >>hlowrd
          >>ello
          >>ello world!
          >>hello
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          列表,元組的切片同理
          —迭代

          可迭代對象:可以直接作用于for循環的對象統稱為可迭代對象(Iterable)
          判斷對象是否可迭代

          from collections import Iterable
          a=isinstanc(對象,Iterable)
          print(a)
          輸出:
          >>True為可迭代
          >>False為不可迭代
          1
          2
          3
          4
          5
          6
          可迭代對象的遍歷
          對字符串的遍歷

          s='hello world!'
          for i in s:
          print(i,end="")
          輸出:
          >>hello world!
          1
          2
          3
          4
          5
          對字典的遍歷

          #遍歷鍵
          d={'name':'Jack','age':12}
          for key in d.keys():
          print(key)
          #遍歷值
          d={'name':'Jack','age':12}
          for value in d.values():
          print(value)
          1
          2
          3
          4
          5
          6
          7
          8
          可迭代對象:字符串,列表,元組,字典,集合
          對列表,集合,元組的遍歷同理
          —生成式

          列表生成式
          語法:[返回的參數 for循環 條件判斷]
          使用方法一 單層循環

          l=[i for i in range(11) if i%2==0]
          print(l)
          輸出:
          >>[0, 2, 4, 6, 8, 10]
          1
          2
          3
          4
          使用方法二 多層循環

          l=[m+n for m in 'ABC' for n in '123']
          print(l)
          輸出:
          >>['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
          1
          2
          3
          4
          例一 對列表中的數據批量操作

          import os
          l=[d.upper() for d in os.listdir('.')]
          print(l)
          輸出:
          >>['2345看圖王.LNK','DESKTOP.INI', 'DEVC++.LNK', 'FIDDLER.LNK']
          1
          2
          3
          4
          5
          例二 取出字典中的鍵值保存到列表中

          d={'a':1,'b':2,'c':3}
          l=[k+'='+str(v) for k,v in d.items()]
          print(l)
          輸出:
          >>['a=1', 'b=2', 'c=3']
          1
          2
          3
          4
          5
          例三 判斷列表中數據的類型

          li=[1,1.5,7j+1,'a',True,False,None]
          p=[type(x) for x in li]
          print(p)
          輸出:
          [<class 'int'>, <class 'float'>, <class 'complex'>, <class 'str'>, <class 'bool'>, <class 'bool'>, <class 'NoneType'>]
          1
          2
          3
          4
          5
          集合生成式
          語法:{返回的參數 for循環 條件判斷}

          s = {i for i in range(1,10) if i%2==0}
          print(s)
          輸出:
          >>{8, 2, 4, 6}
          1
          2
          3
          4
          字典生成式
          語法:{key:value for循環 條件判斷}

          li=['a','b','c','d','e','f','g','h']
          d={i:j for i,j in enumerate(li) if i%2==0}
          print(d)
          輸出:
          >>{0: 'a', 2: 'c', 4: 'e', 6: 'g'}
          1
          2
          3
          4
          5
          —生成器

          生成器:為了節省內存空間,提高程序速度,這種一邊循環一邊計算的機制,稱為生成器。
          next()取值

          li=[1,2,3,4,5]
          g=(x for x in li)
          print(g)
          print(next(g))
          print(next(g))
          print(next(g))
          print(next(g))
          print(next(g))
          輸出:
          >><generator object <genexpr> at 0x0000018F628397C8>
          >>1
          >>2
          >>3
          >>4
          >>5
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          for循環遍歷取值

          li=[1,2,3,4,5]
          g=(x for x in li)
          print(g)
          for i in g:
          print(i)
          輸出:
          >><generator object <genexpr> at 0x0000018F628397C8>
          >>1
          >>2
          >>3
          >>4
          >>5
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          函數的yield返回
          next()取值

          def fun():
          yield 1
          yield 2
          yield 3
          a=fun()
          print(next(a))
          print(next(a))
          print(next(a))
          輸出:
          >>1
          >>2
          >>3
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          for循環遍歷取值

          def fun():
          yield 1
          yield 2
          yield 3
          a=fun()
          print(a)
          for i in a:
          print(i)
          輸出:
          <generator object fun at 0x00000233B8C697C8>
          1
          2
          3
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          例一 斐波拉契數列的推算值生成

          def fib(max):
          n, a, b = 0, 0, 1
          while n < max:
          yield b
          a, b = b, a + b
          n = n + 1
          return 'done'
          a=fib(5)
          for i in a:
          print(i)
          輸出:
          >>1
          >>1
          >>2
          >>3
          >>5
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          generator是非常強大的工具,在Python中,可以簡單地把列表生成式改成generator,也可以通過函數實現復雜邏輯的generator
          要理解generator的工作原理,它是在for循環的過程中不斷計算出下一個元素,并在適當的條件結束for循環。對于函數改成的generator來說,遇到return語句或者執行到函數體最后一行語句,就是結束generator的指令,for循環隨之結束
          請注意區分普通函數和generator函數,普通函數調用直接返回結果
          —迭代器

          迭代器:可以被next()函數調用并不斷返回下一個值的對象稱為迭代器(Iterator)
          可迭代對象轉化為迭代器
          使用iter(可迭代對象)實現將可迭代對象轉化為迭代器

          # 首先獲得Iterator對象:
          it = iter([1, 2, 3, 4, 5])
          # 循環:
          while True:
          try:
          # 獲得下一個值:
          x = next(it)
          print(x)
          except StopIteration:
          # 遇到StopIteration就退出循環
          break
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          凡是可作用于for循環的對象都是Iterable類型
          凡是可作用于next()函數的對象都是Iterator類型,它們表示一個惰性計算的序列
          集合數據類型如list、dict、str等是Iterable但不是Iterator,不過可以通過iter()函數獲得一個Iterator對象
          Python的for循環本質上就是通過不斷調用next()函數實現的

          —定義和實例化

          類的定義

          class Flower(object):
          pass
          1
          2
          添加實例屬性值

          class Flower(object):
          def __init__(self,name,color,height):
          #默認值
          self.name=name
          self.color=color
          self.height=height
          1
          2
          3
          4
          5
          6
          類的實例化

          class Flower(object):
          def __init__(self,name,color,height):
          self.name=name
          self.color=color
          self.height=height
          f=Flower('玫瑰','紅色',20)
          print(f.name)
          print(f.color)
          print(f.height)
          輸出:
          >>玫瑰
          >>紅色
          >>20
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          —實例屬性和類屬性

          類沒有實例屬性時會調用類屬性

          class Flower(object):
          height=20
          def __init__(self,name,color):
          self.name=name
          self.color=color
          f=Flower('玫瑰','紅色')
          print(f.height)
          輸出:
          >>20
          1
          2
          3
          4
          5
          6
          7
          8
          9
          實例屬性的優先級高于類屬性

          class Flower(object):
          height=20
          def __init__(self,name,color,height):
          self.name=name
          self.color=color
          self.height=height
          f=Flower('玫瑰','紅色',10)
          print(f.height)
          輸出:
          >>10
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          刪除實例屬性

          class Flower(object):
          height=20
          def __init__(self,name,color,height):
          self.name=name
          self.color=color
          self.height=height
          f=Flower('玫瑰','紅色',10)
          del f.height
          print(f.height)
          輸出:
          >>20#由于此時實例屬性被刪除,自動調用了類屬性height=20
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          —訪問限制

          私有屬性
          偽私有屬性_attrname:可以訪問但是不要隨意訪問
          私有屬性__attrname:一般不可以訪問

          訪問和修改私有屬性

          訪問私有屬性

          class Student(object):
          def __init__(self,name,score):
          self.__name=name
          self.__score=score

          def get_name(self):
          return self.__name

          def get_score(self):
          return self.__score

          s=Student('Jack',88)
          #通過自定義方法來訪問私有屬性
          print(s.get_name())
          print(s.get_score())
          #直接訪問私有屬性
          print(s._Student__name)
          print(s._Student__score)
          輸出:
          >>Jack
          >>88
          >>Jack
          >>88
          >>a
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          修改私有屬性

          class Student(object):
          def __init__(self,name,score):
          self.__name=name
          self.__score=score

          def get_name(self,newname):
          self.__name=newname
          return self.__name

          def get_score(self,newscore):
          self.__score=newscore
          return self.__score

          s=Student('Jack',88)
          #通過自定義方法修改私有屬性
          print(s.get_name('Peter'))
          print(s.get_score('85'))
          #直接修改私有屬性
          s._Student__name='Mark'
          s._Student__score='86'
          print(s._Student__name)
          print(s._Student__score)
          輸出:
          >>Peter
          >>85
          >>Mark
          >>86
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          —繼承和多態

          —獲取對象信息

          type()函數獲取對象信息
          判斷函數類型

          import types
          def fn():
          pass

          print(type(fn)==types.FunctionType)#判斷是否是自定義函數
          print(type(abs)==types.BuiltinFunctionType)#判斷是否是內置函數
          print(type(lambda x: x)==types.LambdaType)#判斷是否是lambda函數
          print(type((x for x in range(10)))==types.GeneratorType)#判斷是否是生成器類型
          輸出:
          >>True
          >>True
          >>True
          >>True
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          isinstance()函數獲取對象信息
          判斷類對象

          class Animal(object):
          pass
          class Dog(Animal):
          pass
          class Xiaohuang(Dog):
          pass
          a=Xiaohuang()
          b=Dog()
          c=Animal()
          print(isinstance(a,Dog))#Xiaohuang是否屬于Dog類
          print(isinstance(b,Animal))#Dog是否屬于Animal類
          print(isinstance(c,object))#Animal是否屬于object類
          輸出:
          >>True
          >>True
          >>True
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          判斷基本類型數據

          a=[1,2,3,4,5]
          print(isinstance(a,(list,dict)))#判斷a是否屬于列表或者字典類型
          輸出:
          >>True
          1
          2
          3
          4
          dir()獲取一個對象的所有屬性和方法

          s='hello'
          print(dir(s))
          輸出:
          ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
          1
          2
          3
          4
          內置方法的重寫

          class myclass():
          def __len__(self):
          return 10
          def __repr__(self):
          return 'rewrite repr!'
          def __str__(self):
          return 'rewrite str!'

          a=myclass()
          print(len(a)
          print(repr(a))
          print(str(a))
          輸出:
          >>10
          >>rewrite repr!
          >>rewrite str!
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          定制屬性訪問
          hasattr(m,’n’) m:實例 n:類里面的屬性 確定屬性是否存在
          getattr(m,‘n’) m:實例 n:類里面的屬性 得到指定類屬性的值
          setattr(m,’n’,x) m:實例 n:類里面的屬性 x:設置屬性的值 有則改無則添加
          delattr(m,’n’) m:實例 n:類里面的屬性 刪除一個類屬性

          實例屬性的優先級高于類屬性
          4.類的析構(銷毀無用變量)
          5.繼承 重寫
          6.多繼承 重寫
          在類中
          super()可以調用父類里面的方法
          self.方法()可以調用父類里面的方法
          類中查詢相關信息
          1、class查看類名
          格式: 實例.class
          2、dict查看全部屬性,返回屬性和屬性值鍵值對形式
          格式:實例.dict
          3、doc查看對象文檔,即類中(用三個引號引起來的部分)
          格式:類名.dict
          4、bases 查看父類
          格式:類名.base
          5.mro 查看多繼承的情況下,子類調用父類方法時,搜索順序
          格式:子類名.mro 實例.class.mro
          魔術方法:
          str repr call init add

          描述符
          class Myattr():
          def get(self,instance,owner):
          print(“this is get”)
          def set(self,instance,value):
          print(“this is set”)
          def delete(self,instance):
          print(“this is delete”)
          class Myclass():
          attr=Myattr()
          a=Myclass()
          a.attr #訪問屬性來激活__get__方法
          a.attr=1 #賦值來激活__set__方法
          del a.attr #刪除來激活 __delete__方法

          IO編程

          —文件操作

          文件方法
          fp=open(地址,模式,encoding=’utf-8’,errors=’none’/’ignore’) 打開文件
          fp.close() 關閉文件
          with open() as f1,open() as f2: 上下文管理(可以自動關閉文件)
          fp.seek(m) 移動文件指針 當前位置向后移動m個字節
          fp.tell() 查看文件指針
          fp.flush() 刷新緩沖區和fp.close()類似

          文件讀取
          fp.read(m) 文件讀取 讀取m個字節
          fp.readline() 按行文件讀取
          fp.readlins() 列表形式讀取文件

          遍歷文件內容
          for i in fp:
          for i in fp.readlins()
          文件寫入
          fp.write(內容) 文件中寫入內容
          fp.writelines(list) 文件中寫入列表類型內容
          文件內容清空
          fp.truncate() 文件內容清空

          —IO流操作

          引入模塊io
          f=io.StringIO()
          f=io.BytesIO()
          f.getvalue()

          異步IO

          異常

          try:
          print(a) #嘗試運行代碼
          except Exception as e: #將錯誤類型儲存在e中
          print("error!")
          print(e)
          raise Myerror #拋出自定義異常
          else:
          print("right!") #不出異常才執行
          finally:
          print("display all the time") #無論是否異常都會執行
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          模塊和包的管理

          導入一個同級1.py文件 import 1 導入一個只可以被引用不可執行的同級1.py文件import .1
          導入上一級的 1.py文件 import …1
          from a.b.c import hi表示從a下面的b下面的c中導入一個hi函數
          from 和 import 后面既可以接目錄名也可以接不帶后綴的文件名
          import sys
          sys.path.append(r"filedir") filedir:目錄路徑 可以是絕對路徑也可以是相對路徑

          進程和線程

          —多進程

          —多線程

          引入模塊:

          import threading
          1
          實例化 對象=Thread(target=函數名,args=(函數參數,))
          設置線程名 對象.setName(‘線程名’)
          獲取線程名 對象.getName()
          獲取當前線程名 threading.current_thread().name
          開啟線程 對象.start()
          線程守護 對象.Daemon(True)
          主線程結束它的子線程就結束
          線程阻塞對象.join()
          當子線程結束后主線程才結束

          線程鎖
          解決cpu資源競爭問題
          實例化線程鎖對象=threading.Lock()
          上鎖對象.acquire()
          解鎖對象.release(http://www.my516.com)
          ---------------------

          標簽:python核心編程-

          網絡推廣與網站優化公司(網絡優化與推廣專家)作為數字營銷領域的核心服務提供方,其價值在于通過技術手段與策略規劃幫助企業提升線上曝光度、用戶轉化率及品牌影響力。這...

          在當今數字化時代,公司網站已成為企業展示形象、傳遞信息和開展業務的重要平臺。然而,對于許多公司來說,網站建設的價格是一個關鍵考量因素。本文將圍繞“公司網站建設價...

          在當今的數字化時代,企業網站已成為企業展示形象、吸引客戶和開展業務的重要平臺。然而,對于許多中小企業來說,高昂的網站建設費用可能會成為其發展的瓶頸。幸運的是,隨...

          windows server自帶的backup怎么恢復?1. 安裝windows server備份服務。2使用Windows Server Backup進行本地一次性備份。選擇一次性備份后,將啟動一次性備份向導,并在備份向導中選擇備份方法。三。除特殊要求外,不建議備份整個服務器。首先,不建議備份不必要的數據。其次,備份過程相當緩慢。因此,您可以選擇自定義備份。4在選擇要備份的項目頁面中,選擇添加項...

          正能量的歌一直深得人心汪峰-《英雄》北京國安球隊隊歌,聽見這首歌情況下你是不是覺得心潮澎湃?是不是有一種想要去開辟大場面的想法?也許和平時期獲得一場比賽也是英雄。國安隊歌歌詞誰知道???漢化版綠茵場上叫喊著姓名 翠綠色影子也是我們的大牌明星 向著未來 噢 朝著全球 去拼搏大家憧憬的殊榮 獲勝始終屬于你 北京國安永遠爭第一 喔噢…… 北京國安 我們永遠支持你 噢…… 北京國安 大家永遠熱愛你 綠茵場上...

          北京到天津動車多少公里?從北京到天津的距離大約是135.30公里。如果從北京坐動車到天津,按照動車時速120公里計算,一個多小時就能到。京津高鐵c2563首趟列車09336004發車。京津城際鐵路c2017,c2059,c2091,京津城際鐵路c2075,可以坐這幾趟城際高鐵。北京到天津動車多少公里?從北京到天津的動車的公里數大約是60公里。北京到天津動車哪個字母開頭?c字頭是城際列車。單號下行(...

          TOP
          国产初高中生视频在线观看|亚洲一区中文|久久亚洲欧美国产精品|黄色网站入口免费进人
          1. <nobr id="easjo"><address id="easjo"></address></nobr>

              <track id="easjo"><source id="easjo"></source></track>
              1. 
                

              2. <bdo id="easjo"><optgroup id="easjo"></optgroup></bdo>
              3. <track id="easjo"><source id="easjo"><em id="easjo"></em></source></track><option id="easjo"><span id="easjo"><em id="easjo"></em></span></option>