WuHao's Blog

May the force be with you

0%

grammer

  datetime模块

import datetime as d
d.date() 处理日期(年月日)
d.time() 处理事件(时分秒,毫秒)
d.datetime() 处理日期+时间
d.timedelta() 处理时段(时间间隔)
d.date.today()  当前时间
d.tatetime.now()
修改日期格式:
d.date.today().strftime('%Y-%m-%d %H:%M:%S')
d.date.today().__format__('格式')
d.datetime.isoformat()
日期转换成时间戳
timetuple 时间转换成struct_time格式
d.date.today.timetuple() 
time.mktime 返回用秒数来表示时间的浮点数
d.date.fromtimestamp() 将时间戳转换成日期    
timedelta() 方法
eg:今天是今年的第几天:
import datetime
today = datetime.date.today().strftime('%Y%m%d')
#today = today.__format__('%Y%m%d')# __format__ 和strftime()一样
dt = datetime.datetime.strptime(today,"%Y%m%d")
start = today[:4])+'0101'
start = datetime.datetime.strptime(start,"%Y%m%d")
print(int((dt-start).days)+1)


对象持久化

标准库模块
pickle 任意python对象格式化后和解格式化
dbm 实现一个可通过键访问的文件系统,以储存字节串
shelve 按照键把pickle 处理后的对象存储到一个文件中
d = shelve.open()
d[key] =data    value = d[key] del d[key]
d.close()

文本文件基本读写

文件打开
f = open(filename[,mode[,buffering]])
mode第一个字母,表示
f:open()返回的文件对象
mode:可选参数,打开模式和文件类型
buffering:可选参数,打开模式和文件类型
'r'-read,'w'-write,'x'-文件不存在情况下创建并写文件
'a'-append,'+'-读写模式
mode第二个字母是文件类型
't'-txt 'b'-二进制文件


面向对象(object oriented design)(OOP)

类(class)定义的特殊方法 eg.座位(seat)
对象(object) eg.1A号
#class member,instance variable, method(function)

class BankAccount:

#Constructor
def __init__(self,accountNumber,accountName):

    self.accountNumber = accountNumber
    self.accountName   = accountName
    self.balance       = balance

def deposit(self,amount):
    self.balance = self.balance + amount

def withdraw(self):
    self.balance = self.balance - amount


def __str__(self)
    return "({},{})".format(self.accountName,self.balance)
    return "("+ self.accountName + ", " + str(self.balance) + ")"

def __lt__(self,other)
    return self.balance < other.balance
def __gt__(self,other)
    return self.balance > other.balance

new
from ... import BankAccount

b1.withdraw(100.0)
b2.deposit(50.0)

b1 = BankAcount("56789","Tony",500.0)
b2 = BankAcount("12345","Jerry",100.0)


print( b1 )
print( b1 )






算术运算
__add__(self,other),__sub__,__mul__,__div__
反运算
当左操作数不支持相应的操作时被调用
__radd__(self,other),__rsub__,__rmul__,__rdiv__

自定义对象的排序

列表方法sort()