Skip to main content
 首页 » 编程设计

Python:使用类来处理方法调用,就好像类属性是方法参数一样

2024年11月01日9傻小

我的黑客解决方案如下。我非常欢迎发表评论。


我有一个类处理指定时间范围内给定对象组的性能计算(称为 PerformanceAnalysisMixin)。例子是:

class PerformanceAnalysisMixin(object): 
    def set_time_frame(self, time_frame): 
        sets up time frame and sources related info 
 
    def return_over_time_frame(self, time_frame='past_year', values_only=False): 
        return value if values_only else return ('ABC', values) 
 
class Performance(object): 
    # a mythical object which returns the values of calls to 
    # PerformanceAnalyisMixin() as if they were properties 
    # where the calls in are the form: name_for_method.arg0.arg1 
 
>>> pam = PerformanceAnalysisMixin() 
>>> pam.set_time_frame((2010, 2013))  # data for the past three years 
>>> pam.return_over_time_frame('past_year', values_only=True) 
0.13 
>>> pam.return_over_time_frame('past_3_years', values_only=True) 
0.25 

我希望能够以非常惯用的方式调用结果,而不是针对类实例的方法。例如:

>>> perf = Performance(pam) 
>>> # 'time_frame_return' is the name for the method 'return_over_time_frame' 
>>> perf.time_frame_return.past_year 
0.13 
>>> perf.time_frame_return.past_3_years 
0.25 

如果只有几个方法和几个默认时间范围,这将很容易硬编码,但我想要足够的抽象,所以我不需要编写很多排列。我想使用属性调用来为 final方法调用指定适当的参数。

在开始创建此类解决方案之前,我正在此处寻求指导。如果需要,我可以预先填充字典,但我宁愿在动态调用时运行该方法。

我的黑客解决方案:

class F(object): 
    def __init__(self, name, fn=None): 
        self.name = name 
        self.arg_names = [self.name] 
        self.fn = fn 
 
    def __getattr__(self, key): 
        self.key = F(key) 
        self.arg_names.append(self.key.name) 
 
        if key == 'res': 
            _res = self.fn(*self.arg_names[:-1]) 
            self.res = _res 
            return _res 
 
        return self 
 
>>> f = F('get', fn=(lambda a, b, c, d: (a, b, c, d))) 
>>> r = f.some.more.stuff 
>>> r.res 
('get', 'some', 'more', 'stuff') 
>>> g = F('one', fn=(lambda a, b, c, d: (a, b, c, d))) 
>>> g.more.time.ftw.res 
('one', 'more', 'time', 'ftw') 

请您参考如下方法:

你可以这样做:

class MapProperty2Argument(object): 
    def __init__(self, fn): 
        self.fn = fn 
 
    def __getattr__(self, name): 
        return self.fn(name) 
 
class Performance(object): 
    @property 
    def time_frame_return(self): 
        return MapProperty2Argument( 
            PerformanceAnalysisMixin().return_over_time_frame) 

当然,您可能不想为每个函数调用创建 PerformanceAnalysisMixin 对象,而是采用一些现有实例。