Datawhale | Python基礎(chǔ)第7期 Task5

類和對象

類的聲明與類的初始化

使用 class 關(guān)鍵字聲明類

class Student:
    pass

構(gòu)造方法 __init__

class Student:
    # 構(gòu)造函數(shù)
    def __init__(self, name, age):
        self.__name = name
        self.__age = age

# 實(shí)例化類
student = Student('tt', 18)

類方法

在類的內(nèi)部,使用 def 關(guān)鍵字來定義一個方法,與一般函數(shù)定義不同,類方法必須包含參數(shù) self, 且為第一個參數(shù),self 代表的是類的實(shí)例。

def speak(self):
    print("name: %s,  age: %s" %(self.__name, self.__age))

繼承

class People:
    # 定義基本屬性
    name = ''
    age = 0
    # 定義私有屬性
    __weight = 0

    def __init__(self, n, a, w):
        self.name = n
        self.age = a
        self.__weight = w

    def speak(self):
        print("my name is %s, age is %d"%(self.name, self.__weight))

class Student(People):
    grade = ''

    def __init__(self, n, a, w, g):
        # 調(diào)用父類的構(gòu)造函數(shù)
        People.__init__(self, n, a, w)
        self.grade = w
    def speak(self):
        print('student')

python 中支持多繼承,語法如下:

class DerivedClassName(Base1, Base2, Base3):
      <statement-1>
      ...
      <statement-N>

實(shí)例屬性與類屬性

類屬性歸類所有,但所有實(shí)例均可以訪問。

class Student(object):
  name = 'Student'

a = Student()
b = Student()

print(a.name)
print(b.name)
# Student
# Student

# 修改的為實(shí)例屬性
a.name = 'a'
print(a.name)
print(b.name)
# a
# Student

del a.name
print(a.name)
# Student

正則表達(dá)式 與 re模塊

re 模塊

# -*- coding: UTF-8 -*-

import re

# 若匹配成功,則返回 Match 對象,否則返回 None
if re.match(r'^\d{3}-\d{3,8}$', '010-12345'):
  print('ok')
else: 
  print('false')

切分字符串

正則表達(dá)式切分字符串比固定字符串切分更靈活

print('a b   c'.split(' '))
['a', 'b', '', '', 'c']

re.split(r'\s+', 'a b  c  d')
['a', 'b', 'c', 'd']

分組

在正則中使用 () 進(jìn)行分組:

m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
print(m.group(0))
# 010-12345

print(m.group(1))
# 010

編譯

當(dāng)在python使用正則時,re模塊執(zhí)行兩件事:

  1. 編譯正則表達(dá)式
  2. 用編譯后的正則表達(dá)式匹配字符串

出于效率考慮,可以預(yù)編譯正則表達(dá)式:

import re

# 編譯
re_telephone = re.compile(r'^(\d{3})-(\d{3,8})$')

# 使用
m = re_telephone.match('010-12345')
print(m.group(1))

http請求

安裝(若使用 Anaconda,可跳過。已內(nèi)置)

pip install requests

Get 請求

import requests

r = requests.get('https://www.douban.com/')
print(r.status_code)
print(r.text)

Post 請求

r = requests.post('https://accounts.douban.com/login', data={'form_email': 'abc@example.com', 'form_password': '123456'})
print(r.text)

請求傳入Cookie

cs = {'token': '12345', 'status': 'working'}
# timeout 設(shè)置請求超時時間
r = requests.get(url, cookies=cs, timeout=2.5)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容