如何将基于函数的数据管道转换为OOP?

2024-05-14 17:05:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一些数据处理,并构建了几个管道,每个管道都由多个函数组成,这些函数在每个步骤中广泛修改字典。由于不同的管道对相同的数据进行操作,并且具有相似的功能,因此我一直在尝试将其转换为更面向对象的结构。然而,在我开始之前,我已经把自己稍微绑起来了

以以下简化示例为例:

for f in foos:
    y = extract_y_info(f)
    z = extract_z_info(f)
    *some code that does something with y and z*
    
def extract_y_info(f):
    return *some code that extracts y info from f*

def extract_z_info(f):
    return *some code that extracts z info from f*

对我来说,似乎有两种方法可以将其转换为OOP结构。第一种方法与逐个函数的方法非常相似

class foo():
    def __init__(self, x):
        self.x = x

    def extract_y_info(self):
        return *some code that extracts y info from self.x*

    def extract_z_info(self):
        return *some code that extracts z info from self.x*

for f in foo_instances:
    y = b.extract_y_info()
    z = b.extract_z_info()
    *some code that does something with y and z*

另一个选项是修改类的实例:

class foo():
    def __init__(self, x):
        self.x = x

    def extract_y_info(self):
        self.y = *some code that extracts y info from self.x*

    def extract_z_info(self):
        self.z = *some code that extracts z info from self.x*

for f in foo_instances:
    f.extract_y_info()
    f.extract_z_info()
    *some code that does something with f.y and f.z*

这两个选项中有一个比另一个更好吗?还有更好的第三条路吗


Tags: 函数infromselfinfoforreturnthat
1条回答
网友
1楼 · 发布于 2024-05-14 17:05:26

这实际上取决于您的总体设计是什么,在任何给定的时间,您希望您的实例处于什么状态,以及您使用它做什么(换句话说,就是存在y属性本身是指igul,但是…前者对我来说通常更安全。您调用并获得一个值,您不必跟踪,我是否调用了该方法以及该属性或该属性处于什么状态?请注意,您确实应该在构造函数中定义实例属性,否则访问可能不仅令人惊讶,而且是致命的(AttributeError

现在,一个简洁的解决方案解决了上面的一些问题,并且可能适合您在这里访问值所做的工作,可以是property,它本质上允许您访问方法返回的值,就像它是一个实例属性一样:

class foo():
    def __init__(self, x):
        self.x = x

    def extract_y_info(self):
        return #some code that extracts y info from self.x

    y = property(extract_y_info)     

for f in foo_instances:
    print(f"value of f.y = {f.y}")

或者您也可以使用property作为方法装饰器执行相同的操作:

    @property
    def y(self):
        return #some code that extracts y info from self.x

如果获取y非常昂贵,并且它的值在实例的整个生命周期内都不会改变,那么启动Python3.8时,您也可以使用^{}

相关问题 更多 >

    热门问题