Datawhale | Python基础第7期 Task5

2019-05-19  本文已影响0人  youthcity

类和对象

类的声明与类的初始化

使用 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': 'abc@example.com', 'form_password': '123456'})
print(r.text)

请求传入Cookie

cs = {'token': '12345', 'status': 'working'}
# timeout 设置请求超时时间
r = requests.get(url, cookies=cs, timeout=2.5)
上一篇 下一篇

猜你喜欢

热点阅读