You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.4 KiB

8 months ago
from cppy.cp_util import *
8 months ago
# 装饰器改写类
# - 找到以f_开头的方法
# - 将方法函数的返回值赋值给对象的data属性
# - 返回对象自身
8 months ago
def return_self_decorator(cls):
8 months ago
def return_self(func):
# 定义一个闭包函数,用于接收参数
def wrapper(self, *args, **kwargs):
self.data = func(self, *args, **kwargs)
return self # 返回类自身
8 months ago
return wrapper
8 months ago
for name, method in cls.__dict__.items():
# 判断属性是否可调用且属性名以f_开头
if callable(method) and name.startswith('f_'):
8 months ago
# 为类改写属性,将封装后的函数赋值
setattr(cls, name, return_self(method))
8 months ago
return cls
8 months ago
@return_self_decorator
class Flow():
8 months ago
def test(self):
return 'test'
8 months ago
def f_extract_file_words(self, filepath):
return extract_file_words(filepath)
8 months ago
def f_get_frequencies(self):
return get_frequencies(self.data)
8 months ago
def f_sort_dict(self):
return sort_dict(self.data)
8 months ago
8 months ago
def f_print_word_freqs(self, n):
print_word_freqs(self.data, n)
8 months ago
# 顺序调用
Flow().f_extract_file_words(
testfilepath).f_get_frequencies().f_sort_dict().f_print_word_freqs(10)
8 months ago
'''
8 months ago
改写后参与 function flow 功能的方法
- 需要以 'f_' 开头
8 months ago
- 类方法默认不写第一个参数数据都在 .data 里面
8 months ago
仍旧需要特殊的方法写法
所以还是 12种方法比较自然
'''