Datawhale | Python基礎第7期 Task5

類和對象

類的聲明與類的初始化

使用 class 關鍵字聲明類

class Student:
    pass

構造方法 __init__

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

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

類方法

在類的內部,使用 def 關鍵字來定義一個方法,與一般函數定義不同,類方法必須包含參數 self, 且爲第一個參數,self 代表的是類的實例。

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):
        # 調用父類的構造函數
        People.__init__(self, n, a, w)
        self.grade = w
    def speak(self):
        print('student')

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

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

實例屬性與類屬性

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

class Student(object):
  name = 'Student'

a = Student()
b = Student()

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

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

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

正則表達式 與 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')

切分字符串

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

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

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

分組

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

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

print(m.group(1))
# 010

編譯

當在python使用正則時,re模塊執行兩件事:

  1. 編譯正則表達式
  2. 用編譯後的正則表達式匹配字符串

出於效率考慮,可以預編譯正則表達式:

import re

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

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

http請求

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

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': '[email protected]', 'form_password': '123456'})
print(r.text)

請求傳入Cookie

cs = {'token': '12345', 'status': 'working'}
# timeout 設置請求超時時間
r = requests.get(url, cookies=cs, timeout=2.5)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章