python 基础小练习
2018-01-08 12:54
405 查看
#装饰器小练习:既可以输入文本也可以不输入
# -*- coding: utf-8 -*- import time, functools def metric(text): if isinstance(text,str): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): print('%s %s():' % (text, func.__name__)) return func(*args, **kw) return wrapper return decorator else: @functools.wraps(text) def wrapper(*args, **kw): print('%s():' % text.__name__) return text(*args, **kw) return wrapper @metric('execute') def fast(x, y): time.sleep(0.0012) return x + y; @metric def slow(x, y, z): time.sleep(0.1234) return x * y * z; f = fast(11, 22) s = slow(11, 22, 33) if f != 33: print('测试失败!') elif s != 7986: print('测试失败!')
#类和实例:实例只是类的一个例子 class Student(object): def __init__(self, name, score): self.name = name self.score = score def get_grade(self): if self.score >= 90: return 'A' elif self.score >= 60: return 'B' else: return 'C' lisa = Student('Lisa', 99) bart = Student('Bart', 59) print(lisa.name, lisa.get_grade()) print(bart.name, bart.get_grade())
# 父类与子类:继承 class animal(object): def run(self): print('animal is running...') class Timer(object): def run(self): print('Start...') def run_twice(animal): animal.run() animal.run() run_twice(Timer())
结果:Start...Start...
#测试切片:去除首尾的空格
def trim(s): t=len(s) w1=0 w2=t while (w1<w2): if s[w1]==' ': w1=w1+1 if s[w2-1]==' ': w2=w2-1 if s[w1]!=' 'and s[w2-1]!=' ': break s=s[w1:w2] print('s=',s) return s if trim('hello ') != 'hello': print('测试失败!') elif trim(' hello') != 'hello': print('测试失败!') elif trim(' hello ') != 'hello': print('测试失败!') elif trim(' hello world ') != 'hello world': print('测试失败!') elif trim('') != '': print('测试失败!') elif trim(' ') != '': print('测试失败!') else: print('测试成功!')
结果:
s= hello s= hello s= hello s= hello world s= s= 测试成功!
#假设你获取了用户输入的日期和时间如2015-1-21 9:01:30,以及一个时区信息如UTC+5:00,均是str,请编写一个函数将其转换为timestamp:
import re from bs4 import BeautifulSoup import pprint import os from datetime import datetime,timezone,timedelta def to_timestamp(dt_str,tz_str): cday=datetime.strptime(dt_str,'%Y-%m-%d %H:%M:%S') t=tz_str[3:5] UT=int(t) ca=re.split(r'[- :]',dt_str) timefinal=cday.replace(tzinfo=timezone(timedelta(hours=UT))) return timefinal.timestamp() t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00') assert t1 == 1433121030.0, t1 t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-9:00') assert t2 == 1433121030.0, t2 print('ok')
结果:ok
相关文章推荐
- 继承父类,调用父类中的方法 分类: python 小练习 python基础学习 2014-01-10 17:54 325人阅读 评论(0) 收藏
- python-post上传图片基础练习5
- Python基础练习2
- fileinput模块 分类: python基础学习 python 小练习 python Module 2013-08-15 17:18 417人阅读 评论(0) 收藏
- Python基础练习——字符串和字典的转换
- python基础知识练习
- python基础练习三
- 【14】Python100例基础练习(1)
- python基础练习(四)—— 读取文件内容
- python基础练习2
- python数据持久存储:pickle模块的基本使用 分类: python python基础学习 python 小练习 2013-06-17 14:41 209人阅读 评论(0) 收藏
- python基础2练习
- Android逆向-python基础练习2
- 确定你掌握了pandas?进来看看——python中pandas入门基础练习
- python基础练习四
- python基础练习之几个简单的游戏
- Python 基础练习
- Python 基础练习 PAT水题(三)
- python基础练习---打印九九乘法表!
- Python 基础练习01