标签:port 没有 pre 可变参 like 赋值 bug list 添加
2015.8.5
def add(x,y,f):
return f(x)+f(y)
print add(4,5,abs)
def format_name(s):
a=s[:1].upper()+s[1:].lower()
return a
print map(format_name,[‘adam‘,‘LISA‘,‘barT‘])
def prod(x, y):
return x*y
print reduce(prod,[2,4,5,7,12])
print reduce(prod,[2,4,5,7,12],100)
import math
def is_sqr(x):
r=int(math.sqrt(x))
return r*r==x
print filter(is_sqr, range(1,100))
def cmp_ignore_case(s1, s2):
u1=s1.upper()
u2=s2.upper()
if u1<u2:
return-1
if u1==u2:
return0
if u1>u2:
return1
print sorted([‘bob‘,‘about‘,‘Zoo‘,‘Credit‘],cmp_ignore_case)
def calc_prod(lst):
def g():
def d(x,y):
return x * y
return reduce(d,lst,1)
return g
f = calc_prod([1,2,3,4])
print f()
def count():
fs =[]
for i in range(1,4):
def f(x):
def g():
return x*x;
return g
r=f(i)
fs.append(r)
return fs
f1, f2, f3 = count()
print f1(), f2(), f3()
print filter(lambda s:s and len(s.strip())>0,[‘test‘,None,‘‘,‘str‘,‘ ‘,‘END‘])
def log(f):
def fn(x):
print‘call ‘+ f.__name__ +‘()...‘
return f(x)
return fn
@log
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
#此处代码如下
factorial=log(
def log(f):
def fn(*args,**kw):
print‘call ‘+ f.__name__ +‘()...‘
return f(*args,**kw)
return fn
@log
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
import time
def performance(f):
def fn(*args,**kw):
t1=time.time()
r=f(*args,**kw)
t2=time.time()
print‘call %s() in %fs‘%(f.__name__,(t2-t1))
return r
return fn
@performance
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
def log(str):
def log_decorator(f):
def fn(*args,**kw):
print‘call [%s] %s()...‘%(str,f.__name__)
return f(*args,**kw)
return fn
return log_decorator
@log(‘debug‘)
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
#factorial=log(factorial)
print factorial(10)
import time
def performance(unit):
def pp(f):
def ff(*a,**k):
t1=time.time()
r=f(*a,**k)
t2=time.time()
print‘call %s() in %f%s‘%(f.__name__,t2-t1,unit)
return r
return ff
return pp
@performance(‘ms‘)
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
import functools
def log(f):
#@functools.wraps(f)
def wrapper(*args,**kw):
print‘call...‘
return f(*args,**kw)
return wrapper
@log
def ff():
return1
print ff.__name__
import time, functools
def performance(unit):
def pp(f):
@functools.wraps(f)
def ff(*rags,**k):
t1=time.time()
r=f(*rags,**k)
t2=time.time()
print‘call %s in %f%s‘%(f.__name__,t2-t1,unit)
return r
return ff
return pp
@performance(‘ms‘)
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
print factorial.__name__
import functools
sorted_ignore_case = functools.partial(sorted,cmp=lambda s1,s2:cmp(s1.upper(),s2.upper()))
print sorted_ignore_case([‘bob‘,‘about‘,‘Zoo‘,‘Credit‘])
#test.py
import p1.unit
print p1.unit.f(2,1)
import os.path
print os.path.isdir(r‘/data/webroot/resource/python‘)
print os.path.isfile(r‘/data/webroot/resource/python/test.txt‘)
try:
from cStringIO importStringIO
exceptImportError:
fromStringIOimportStringIO
try:
import json
exceptImportError:
import simplejson as json
print json.dumps({‘python‘:2.7})
from __future__ import division#若不引入,print 10/3输出3,引入输出3.3333333
import p1.hello
print10/3
print p1.hello.factorial(10)
from __future__ import unicode_literals
s = b‘am I an unicode?‘
print isinstance(s, unicode)
classPerson(object):
pass
classPerson(object):
def __init__(self,name):#构造函数
self.name=name
xiaoming =Person(‘xiaoming‘)
xiaohong =Person(‘xiaohong‘)
print xiaoming.name
print xiaohong.name
print xiaoming.name==xiaohong.name
classPerson(object):
pass
p1 =Person()
p1.name =‘Bart‘
p2 =Person()
p2.name =‘Adam‘
p3 =Person()
p3.name =‘Lisa‘
L1 =[p1, p2, p3]
L2 = sorted(L1,lambda p1,p2:cmp(p1.name,p2.name))
print L2[0].name
print L2[1].name
print L2[2].name
def foo1(arg1,arg2,*arg,**keywords):
print"arg1 parameters is ",arg1
print"arg2 parameters is ",arg2
print"Arbitrary parameter is ", arg
print"keywords parameter is ",keywords
foo1(1,2,3,4,5,6,k1=1,k2=2,k3=3)
classPerson(object):
def __init__(self,name,sex,bor,*args,**kw):
self.name=name
self.sex=sex
self.bor=bor
for k,v in kw.iteritems():
setattr(self,k,v)
for c in args:
setattr(self,c)
xiaoming =Person(‘Xiao Ming‘,‘Male‘,‘1990-1-1‘, job=‘Student‘,job2=‘sty‘)
print xiaoming.name
print xiaoming.job
print xiaoming.job2
classPerson(object):
def __init__(self, name, score):
self.name=name
self.__score=score
p =Person(‘Bob‘,59)
print p.name
print p.__score
classPerson(object):
count=0
def __init__(self,name):
Person.count=Person.count+1
self.name=name
p1 =Person(‘Bob‘)
printPerson.count
p2 =Person(‘Alice‘)
printPerson.count
p3 =Person(‘Tim‘)
printPerson.count
classPerson(object):
__count =0
count=0
def __init__(self, name):
Person.__count=Person.__count+1
self.name=name
p1 =Person(‘Bob‘)
p2 =Person(‘Alice‘)
printPerson.__count
printPerson.count
#-*- coding:utf-8 -*-
classPerson(object):
def __init__(self, name, score):
self.__score=score
self.name=name
def get_grade(self):
if self.__score>=80:
return‘优秀‘
if self.__score>=60:
return‘及格‘
if self.__score<60:
return‘不及格‘
p1 =Person(‘Bob‘,90)
p2 =Person(‘Alice‘,65)
p3 =Person(‘Tim‘,48)
print p1.get_grade()
print p2.get_grade()
print p3.get_grade()
import types
def fn_get_grade(self):
if self.score >=80:
return‘A‘
if self.score >=60:
return‘B‘
return‘C‘
classPerson(object):
def __init__(self, name, score):
self.name = name
self.score = score
p1 =Person(‘Bob‘,90)
p1.get_grade = types.MethodType(fn_get_grade, p1,Person)
print p1.get_grade()
# => A
p2 =Person(‘Alice‘,65)
print p2.get_grade()
# ERROR: AttributeError: ‘Person‘ object has no attribute ‘get_grade‘
# 因为p2实例并没有绑定get_grade
classPerson(object):
def __init__(self, name, score):
self.name = name
self.score = score
self.get_grade =lambda:‘A‘
p1 =Person(‘Bob‘,90)
print p1.get_grade
print p1.get_grade()
classPerson(object):
count=0
@classmethod
def howMany(cls):
return cls.count
def __init__(self,name):
self.name=name
Person.count=Person.count+1
printPerson.howMany()
p1=Person(‘xiaoming‘)
printPerson.howMany()
classPerson(object):
__count =0
def __init__(self,name):
Person.__count=Person.__count+1
self.name=name
@classmethod
def how_many(cls):
return cls.__count
printPerson.how_many()
p1 =Person(‘Bob‘)
printPerson.how_many()
classPerson(object):
count=0
@classmethod
def howMany(cls):
return cls.count
def __init__(self,name,gender):
self.name=name
Person.count=Person.count+1
classStudent(Person):
def __init__(self,name,gender,school,score):
super(Student,self).__init__(name,gender)
self.school=school
self.score=score
printPerson.howMany()
p1=Person(‘xiaoming‘,‘m‘)
s1=Student(‘n‘,‘s‘,‘d‘,11)
print s1.name
printPerson.howMany()
classPerson(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
classStudent(Person):
def __init__(self, name, gender, score):
super(Student, self).__init__(name, gender)
self.score = score
classTeacher(Person):
def __init__(self, name, gender, course):
super(Teacher, self).__init__(name, gender)
self.course = course
t =Teacher(‘Alice‘,‘Female‘,‘English‘)
print isinstance(t,Person)
print isinstance(t,Student)
print isinstance(t,Teacher)
print isinstance(t,object)
classPerson(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
def whoAmI(self):
return‘I am a Person, my name is %s‘% self.name
classStudent(Person):
def __init__(self, name, gender, score):
super(Student, self).__init__(name, gender)
self.score = score
def whoAmI(self):
return‘I am a Student, my name is %s‘% self.name
classTeacher(Person):
def __init__(self, name, gender, course):
super(Teacher, self).__init__(name, gender)
self.course = course
def whoAmI(self):
return‘I am a Teacher, my name is %s‘% self.name
def who_am_i(x):
print x.whoAmI()
p =Person(‘Tim‘,‘Male‘)
s =Student(‘Bob‘,‘Male‘,88)
t =Teacher(‘Alice‘,‘Female‘,‘English‘)
who_am_i(p)
who_am_i(s)
who_am_i(t)
import json
classStudents(object):
def read(self):
return r‘["Tim", "Bob", "Alice"]‘
s =Students()
print json.load(s)
classPerson(object):
pass
classStudent(Person):
pass
classTeacher(Person):
pass
classSkillMixin(object):
pass
classBasketballMixin(SkillMixin):
def skill(self):
return‘basketball‘
classFootballMixin(SkillMixin):
def skill(self):
return‘football‘
classBStudent(BasketballMixin,Student):
pass
classFTeacher(FootballMixin,Teacher):
pass
s =BStudent()
print s.skill()
t =FTeacher()
print t.skill()
#-*- coding:utf-8 -*-
classPerson(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
classStudent(Person):
def __init__(self, name, gender, score):
super(Student, self).__init__(name, gender)
self.score = score
def whoAmI(self):
return‘I am a Student, my name is %s‘% self.name
s =Student(‘Bob‘,‘Male‘,88)
print type(s)
print getattr(s,‘name‘)
print getattr(s,‘age‘,20)#不存在age值则返回默认值20
setattr(s,‘name‘,‘Adam‘)
print dir(s)
#-*- coding:utf-8 -*-
classPerson(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
s =Person(‘Bob‘,‘Male‘)
print s
print s.__str__()#输出结果同上__str__()便是一个特殊方法,用于显示给用户
classPerson(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
classStudent(Person):
def __init__(self, name, gender, score):
super(Student, self).__init__(name, gender)
self.score = score
def __str__(self):
return‘Student: %s,%s,%s‘%(self.name,self.gender,self.score)
__repr__=__str__
s =Student(‘Bob‘,‘male‘,88)
print s
classStudent(object):
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return‘(%s: %s)‘%(self.name, self.score)
__repr__ = __str__
def __cmp__(self, s):
if self.score<s.score:
return-1
elif self.score==s.score:
return0
else:
return1
L =[Student(‘Tim‘,99),Student(‘Bob‘,88),Student(‘Alice‘,99)]
print sorted(L)
classFib(object):
def __init__(self, num):
a,b,L=0,1,[]
for n in range(num):
L.append(a)
a,b=b,a+b
self.numbers=L
def __str__(self):
return str(self.numbers)
__repr__=__str__
def __len__(self):
return len(self.numbers)
f =Fib(10)
print f
print len(f)
def gcd(a,b):#处理有理数归约
if b==0:
return a
return gcd(b,a%b)
classRational(object):
def __init__(self, p, q):
self.p = p
self.q = q
def __add__(self, r):
returnRational(self.p * r.q + self.q * r.p, self.q * r.q)
def __sub__(self, r):
returnRational(self.p*r.q-self.q*r.p,self.q*r.q)
def __mul__(self, r):
returnRational(self.p*r.p,self.q*r.q)
def __div__(self, r):
returnRational(self.p*r.q,self.q*r.p)
def __str__(self):
g=gcd(self.p,self.q)
return‘%s/%s‘%(self.p/g,self.q/g)##########
__repr__ = __str__
r1 =Rational(1,2)
r2 =Rational(1,4)
print r1 + r2
print r1 - r2
print r1 * r2
print r1 / r2
classRational(object):
def __init__(self, p, q):
self.p = p
self.q = q
def __int__(self):
return self.p // self.q
def __float__(self):
return float(self.p)/self.q
print float(Rational(7,2))
print float(Rational(1,3))
classStudent(object):
def __init__(self, name, score):
self.name = name
self.__score = score
@property #如get方法
def score(self):
return self.__score
@score.setter #如set方法
def score(self, score):
if score <0or score >100:
raiseValueError(‘invalid score‘)
self.__score = score
@property
def grade(self):
if self.score<60:
return‘C‘
if self.score<80:
return‘B‘
return‘A‘
s =Student(‘Bob‘,59)
print s.grade
s.score =60
print s.grade
s.score =99
print s.grade
classStudent(object):
__slots__ =(‘name‘,‘gender‘,‘score‘)
def __init__(self, name, gender, score):
self.name = name
self.gender = gender
self.score = score
s =Student(‘Bob‘,‘male‘,59)
s.name =‘Tim‘# OK
s.score =99# OK
s.grade =‘A‘
classPerson(object):
__slots__ =(‘name‘,‘gender‘)
def __init__(self, name, gender):
self.name = name
self.gender = gender
classStudent(Person):
__slots__ =(‘score‘,)#当只有一个属性是,之后需要加个,
def __init__(self,name,gender,score):
super(Student,self).__init__(name,gender)
self.name=name
self.gender=gender
self.score=score
s =Student(‘Bob‘,‘male‘,59)
s.name =‘Tim‘
s.score =99
print s.score
classPerson(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
def __call__(self, friend):
print‘My name is %s...‘% self.name
print‘My friend is %s...‘% friend
p=Person(‘bob‘,‘man‘)
p(‘tim‘)
classFib(object):
def __call__(self,num):
a,b,L=0,1,[]
for n in range(num):
L.append(a)
a,b=b,a+b
return L
f =Fib()
print f(10)
标签:port 没有 pre 可变参 like 赋值 bug list 添加
原文地址:http://www.cnblogs.com/kinmos/p/6829851.html