Last active
April 1, 2017 10:34
-
-
Save gt11799/6f2d4fc567a5fcc6676e02356f692fc7 to your computer and use it in GitHub Desktop.
functool module practise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
functool中的total_ordring的练习 | |
total_ordring是用来补全比较方法的 | |
wraps是用来改变函数的显示 | |
partial是可以生成一个新的函数,这个函数的某个参数可以提前指定 | |
唉,不知道该怎么描述 | |
''' | |
import random | |
from functools import total_ordering, wraps, partial, partialmethod | |
@total_ordering | |
class Student(object): | |
def __init__(self, student_id, score): | |
self.id = student_id | |
self.score = score | |
self.count = 0 | |
def __eq__(self, other): | |
return self.score == other.score | |
def __lt__(self, other): | |
return self.score < other.score | |
def __repr__(self): | |
return '%s_id:%s, score:%s' % (self.__class__, self.id, self.score) | |
def add(self, count): | |
self.count += count | |
# new in python3 | |
incr = partialmethod(add, 1) | |
def test_student_sort(): | |
print('=====test_student_sort=====') | |
to_sort = map(lambda x: Student(x + 1, int(random.random() * 100)), range(200)) | |
print('__ge__' in dir(Student)) | |
print(sorted(to_sort, reverse=True)[-10:]) | |
def decorator(func): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
return func(*args, **kwargs) | |
return wrapper | |
@decorator | |
def print_params(x, y): | |
print('x: %s, y: %s' % (x, y)) | |
def test_wraps(): | |
print('=====test_wraps=====') | |
print('function is %s' % print_params) | |
def test_partial(): | |
print('=====test_partial=====') | |
func = partial(print_params, x=3) | |
func(y=10) | |
print('=====test_method_partial=====') | |
s = Student(17, 100) | |
s.add(100) | |
s.incr() | |
print('student count is %s' % s.count) | |
if __name__ == '__main__': | |
test_student_sort() | |
test_wraps() | |
test_partial() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment