您的位置:首页 > 编程语言 > Python开发

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


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  原创