将过程转换为面向对象:Python3.4

2024-06-16 11:37:37 发布

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

为了更“pythonic”(更模块化),我想将我的过程代码转换为Class。这里感兴趣的对象是husband和{}的婚姻,这里称之为{},夫妻之间有一些共同的和一些独特的属性。这些属性是通过yield从文件填充到生成器对象中的。在

我想把这两个解析函数get_husband和{}(可能还有最后一个zip函数)作为一个类函数来执行,它仍然使用迭代器对象来填充marriage.firstnamemarriage.husbandscoremarriage.wifescore的属性,然后,我将创建一些方法,在从生成器输出每个marriage对象时,对这些对象的信息执行进一步的分析。在

但我不确定解析定义是否最好作为方法保存,因为我将返回self,这不是我下一步工作所需的生成器。。。在

from itertools import izip

def get_husband(husbandfile):
    lastname, firstname, husbandscore = '', '', ''
    for line in husbandfile.readlines():
        # Parse files to fill out the names, wifescores in wifefile
        yield name, husbandscore

def get_wife(wifefile):
    lastname, firstname, wifescore = '', '',''
    for line in wifefile.readlines():
        # Parse files to fill out the names, wifescores in wifefile
        yield name, wifescore

def make_family(husbandfile, wifefile):
    for husband, wife in izip(get_husband(husbandfile), get_wife(wifefile)):
        if husband[0] == wife[0]:
            lastname = husband[0]
            parentscore = husband[1] + wife[0]

            yield lastname, parentscore
        else:
            raise Exception("These two aren't married

你认为把它作为一个类来考虑的最好方法是什么


Tags: 对象函数inget属性firstnameyieldmarriage