student类中的属性score可以直接调用,赋值,但无法判读赋予的数值的合理性,也无法实现只读属性。
于是引入set方法和get方法。
get方法负责获取score属性的值,set方法负责判断数值的合理性并给score属性赋值。但是每次都要调用方法不如直接写属性来得方便。
于是引入内置装饰器@property
property是一个类,property=属性(get,set,del)。里面带@property , @x.get , @x.del 三个装饰器。
装饰器@property可以将方法变为属性。
于是引入set方法和get方法。
get方法负责获取score属性的值,set方法负责判断数值的合理性并给score属性赋值。但是每次都要调用方法不如直接写属性来得方便。
于是引入内置装饰器@property
property是一个类,property=属性(get,set,del)。里面带@property , @x.get , @x.del 三个装饰器。
装饰器@property可以将方法变为属性。
2019-04-09
def performance(f):
def new_fn(n):
start = time.time()
a=f(n)
end = time.time()-start
return 'call '+f.__name__+'() in %s' %end,a
return new_fn
def new_fn(n):
start = time.time()
a=f(n)
end = time.time()-start
return 'call '+f.__name__+'() in %s' %end,a
return new_fn
2019-04-08
def calc_prod(lst):
def prod():
sum=1
for x in lst:
sum *= x
return sum
return prod
f = calc_prod([1, 2, 3, 4])
print f()
def prod():
sum=1
for x in lst:
sum *= x
return sum
return prod
f = calc_prod([1, 2, 3, 4])
print f()
2019-04-08
def calc_prod(lst):
def prod():
return reduce(lambda x,y:x*y,lst)
return prod
f = calc_prod([1, 2, 3, 4])
print f()
def prod():
return reduce(lambda x,y:x*y,lst)
return prod
f = calc_prod([1, 2, 3, 4])
print f()
2019-04-08
import math
def is_sqr(x):
num = str(math.sqrt(x)).split('.')
return num[len(num)-1] == '0'
print filter(is_sqr, range(1, 101))
def is_sqr(x):
num = str(math.sqrt(x)).split('.')
return num[len(num)-1] == '0'
print filter(is_sqr, range(1, 101))
2019-04-07
def format_name(s):
return s.capitalize()
print map(format_name, ['adam', 'LISA', 'barT'])
return s.capitalize()
print map(format_name, ['adam', 'LISA', 'barT'])
2019-04-07
def format_name(s):
# return s[0].upper()+s[1:].lower()
return s.title()
print map(format_name, ['adam', 'LISA', 'barT'])
# return s[0].upper()+s[1:].lower()
return s.title()
print map(format_name, ['adam', 'LISA', 'barT'])
2019-04-06
import math
def is_sqr(x):
c=(x/(round(math.sqrt(x)))==math.sqrt(x))
return x and c
print filter(is_sqr, range(1,100))
def is_sqr(x):
c=(x/(round(math.sqrt(x)))==math.sqrt(x))
return x and c
print filter(is_sqr, range(1,100))
2019-04-04
def count():
fs = []
for i in range(1, 4):
def f(x=i):
return x*x
fs.append(f)
return fs
f1, f2, f3 = count()
print f1(), f2(), f3()
fs = []
for i in range(1, 4):
def f(x=i):
return x*x
fs.append(f)
return fs
f1, f2, f3 = count()
print f1(), f2(), f3()
2019-04-03
class Person(object):
def __init__(self, name, gender, **kw):
self.name = name
self.gender = gender
for k, v in kw.iteritems():
setattr(self,k,v)
p = Person('Bob', 'Male', age=18, course='Python')
print p.age
print p.course
def __init__(self, name, gender, **kw):
self.name = name
self.gender = gender
for k, v in kw.iteritems():
setattr(self,k,v)
p = Person('Bob', 'Male', age=18, course='Python')
print p.age
print p.course
2019-04-03
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
2019-04-03