Python 3 教程 在线

1168Python3 标准库概览

时间和日期补充

常用时间处理方法

  • 今天 today = datetime.date.today()
  • 昨天 yesterday = today - datetime.timedelta(days=1)
  • 上个月 last_month = today.month - 1 if today.month - 1 else 12
  • 当前时间戳 time_stamp = time.time()
  • 时间戳转datetime datetime.datetime.fromtimestamp(time_stamp)
  • datetime转时间戳 int(time.mktime(today.timetuple()))
  • datetime转字符串 today_str = today.strftime("%Y-%m-%d")
  • 字符串转datetime today = datetime.datetime.strptime(today_str, "%Y-%m-%d")
  • 补时差 today + datetime.timedelta(hours=8)

1167Python3 标准库概览

关于urlopen的补充

#处理get请求,不传data,则为get请求

import urllib
from urllib.request import urlopen
from urllib.parse import urlencode

url='http://www.xxx.com/login'
data={"username":"admin","password":123456}
req_data=urlencode(data)#将字典类型的请求数据转变为url编码
res=urlopen(url+'?'+req_data)#通过urlopen方法访问拼接好的url
res=res.read().decode()#read()方法是读取返回数据内容,decode是转换返回数据的bytes格式为str

print(res)
#处理post请求,如果传了data,则为post请求

import urllib
from urllib.request import Request
from urllib.parse import urlencode

url='http://www.xxx.com/login'
data={"username":"admin","password":123456}
data=urlencode(data)#将字典类型的请求数据转变为url编码
data=data.encode('ascii')#将url编码类型的请求数据转变为bytes类型
req_data=Request(url,data)#将url和请求数据处理为一个Request对象,供urlopen调用
with urlopen(req_data) as res:
    res=res.read().decode()#read()方法是读取返回数据内容,decode是转换返回数据的bytes格式为str

print(res)

1166Python3 面向对象

关于 __name__

首先需要了解 __name__ 是属于 python 中的内置类属性,就是它会天生就存在与一个 python 程序中,代表对应程序名称。

比如所示的一段代码里面(这个脚本命名为 pcRequests.py),我只设了一个函数,但是并没有地方运行它,所以当 run 了这一段代码之后我们有会发现这个函数并没有被调用。但是当我们在运行这个代码时这个代码的 __name__ 的值为 __main__ (一段程序作为主线运行程序时其内置名称就是 __main__)。

import requests
class requests(object):
    def __init__(self,url):
        self.url=url
        self.result=self.getHTMLText(self.url)
    def getHTMLText(url):
        try:
            r=requests.get(url,timeout=30)
            r.raise_for_status()
            r.encoding=r.apparent_encoding
            return r.text
        except:
            return "This is a error."
print(__name__)

结果:

__main__
Process finished with exit code 0

当这个 pcRequests.py 作为模块被调用时,则它的 __name__ 就是它自己的名字:

import pcRequestspcRequestsc=pcRequestsc.__name__

结果:

'pcRequests'

看到这里应该能明白,自己的 __name__ 在自己用时就是 main,当自己作为模块被调用时就是自己的名字,就相当于:我管自己叫我自己,但是在朋友眼里我就是小仙女一样

1165Python3 面向对象

1164Python3 面向对象

反向运算符重载:

  • __radd__: 加运算
  • __rsub__: 减运算
  • __rmul__: 乘运算
  • __rdiv__: 除运算
  • __rmod__: 求余运算
  • __rpow__: 乘方

复合重载运算符:

  • __iadd__: 加运算
  • __isub__: 减运算
  • __imul__: 乘运算
  • __idiv__: 除运算
  • __imod__: 求余运算
  • __ipow__: 乘方

运算符重载的时候:

#!/usr/bin/python3

class Vector:
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def __str__(self):
        return 'Vector (%d, %d)' % (self.a, self.b)

    def __repr__(self):
        return 'Vector (%d, %d)' % (self.a, self.b)

    def __add__(self,other):
        if other.__class__ is Vector:
            return Vector(self.a + other.a, self.b + other.b)
        elif other.__class__ is int:
            return Vector(self.a+other,self.b)

    def __radd__(self,other):
        """反向算术运算符的重载
        __add__运算符重载可以保证V+int的情况下不会报错,但是反过来int+V就会报错,通过反向运算符重载可以解决此问题
        """

        if other.__class__ is int or other.__class__ is float:
            return Vector(self.a+other,self.b)
        else:
            raise ValueError("值错误")

    def __iadd__(self,other):
        """复合赋值算数运算符的重载
        主要用于列表,例如L1+=L2,默认情况下调用__add__,会生成一个新的列表,
        当数据过大的时候会影响效率,而此函数可以重载+=,使L2直接增加到L1后面
        """

        if other.__class__ is Vector:
            return Vector(self.a + other.a, self.b + other.b)
        elif other.__class__ is int:
            return Vector(self.a+other,self.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)
print (v1+5)
print (6+v2)