0

仍然对 python 及其神奇的函数式编程感到有些困惑,所以我倾向于发现自己编写的代码更倾向于 Java 编程范式,而不是 Idiomatic Python。

我的问题有点相关:如何使自定义类成为 Python 中的集合

唯一的区别是我有嵌套对象(使用组合)。VirtualPage对象由PhysicalPage对象的列表组成。我有一个函数,它可以获取一个PhyscialPage对象列表并将所有细节合并到一个名为PageBoundary的单个命名元组中。本质上它是一个序列化函数,它可以输出一个由整数范围组成的元组,该整数范围代表物理页面和页面中的行号。由此,我可以轻松地对 VirtualPages 进行排序和排序(至少是这样的想法):

PageBoundary = collections.namedtuple('PageBoundary', 'begin end')

我还有一个函数可以采用PageBoundary namedtuple并将元组反序列化或扩展为PhysicalPages列表。最好不要更改这两个数据存储类,因为它会破坏任何下游代码。

这是我的自定义 python2.7 类的片段。它由很多东西组成,一个是包含对象PhysicalPage的列表:

class VirtualPage(object):
    def __init__(self, _physical_pages=list()):
        self.physcial_pages = _physcial_pages


class PhysicalPage(object):
    # class variables: number of digits each attribute gets
    _PAGE_PAD, _LINE_PAD = 10, 12 

    def __init__(self, _page_num=-1):
        self.page_num = _page_num
        self.begin_line_num = -1
        self.end_line_num = -1

    def get_cannonical_begin(self):
        return int(''.join([str(self.page_num).zfill(PhysicalPage._PAGE_PAD),
                    str(tmp_line_num).zfill(PhysicalPage._LINE_PAD) ]))

    def get_cannonical_end(self):
        pass # see get_cannonical_begin() implementation

    def get_canonical_page_boundaries(self):
        return PageBoundary(self.get_canonical_begin(), self.get_canonical_end())

我想利用一些模板化集合(来自 python 集合模块)来轻松地作为列表或VirtualPage类集进行排序和比较。还想对我的数据存储类的布局提出一些建议:VirtualPagePhysicalPage

给定一个VirtualPages序列或如下例所示:

vp_1 = VirtualPage(list_of_physical_pages)
vp_1_copy = VirtualPage(list_of_physical_pages)
vp_2 = VirtualPage(list_of_other_physical_pages)

我想轻松回答这样的问题:

>>> vp_2 in vp_1 
False
>>> vp_2 < vp_1
True
>>> vp_1 == vp_1_copy
True

马上,很明显VirtualPage类需要调用 get_cannonical_page_boundaries 甚至实现函数本身。至少它应该遍历它的PhysicalPage列表以实现所需的功能(lt () 和eq ()),以便我可以比较 b/w VirtualPages

1.)目前我正在努力实现一些比较功能。一个很大的障碍是如何比较一个元组?我是否通过创建扩展某种类型的集合的自定义类来创建自己的lt () 函数:

import collections as col
import functools

@total_ordering
class AbstractVirtualPageContainer(col.MutableSet):

    def __lt__(self, other):
        '''What type would other be?
        Make comparison by first normalizing to a comparable type: PageBoundary
        '''
        pass

2.) 比较函数的实现是否应该存在于VirtualPage类中?

我倾向于某种类型的 Set 数据结构,因为我正在建模的数据的属性具有唯一性的概念:即物理页面值不能重叠并且在某种程度上充当链接列表。通过@decorator 函数实现的setter 或getter 函数在这里也有用吗?

4

1 回答 1

0

我想你想要下面的代码。未测试;当然没有针对您的应用程序或您的数据、YMMV 等进行测试。

from collections import namedtuple

# PageBoundary is a subclass of named tuple with special relational
# operators. __le__ and __ge__ are left undefined because they don't
# make sense for this class.
class PageBoundary(namedtuple('PageBoundary', 'begin end')):
    # to prevent making an instance dict (See namedtuple docs)
    __slots__ = ()

    def __lt__(self, other):
        return self.end < other.begin

    def __eq__(self, other):
        # you can put in an assertion if you are concerned the
        # method might be called with the wrong type object
        assert isinstance(other, PageBoundary), "Wrong type for other"

        return self.begin == other.begin and self.end == other.end

    def __ne__(self, other):
        return not self == other

    def __gt__(self, other):
        return other < self


class PhysicalPage(object):
    # class variables: number of digits each attribute gets
    _PAGE_PAD, _LINE_PAD = 10, 12 

    def __init__(self, page_num):
        self.page_num = page_num

        # single leading underscore is 'private' by convention
        # not enforced by the language
        self._begin = self.page_num * 10**PhysicalPage._LINE_PAD + tmp_line_num
        #self._end = ...however you calculate this...                    ^ not defined yet

        self.begin_line_num = -1
        self.end_line_num = -1

    # this serves the purpose of a `getter`, but looks just like
    # a normal class member access. used like x = page.begin  
    @property
    def begin(self):
        return self._begin

    @property
    def end(self):
        return self._end

    def __lt__(self, other):
        assert(isinstance(other, PhysicalPage))
        return self._end < other._begin

    def __eq__(self, other):
        assert(isinstance(other, PhysicalPage))
        return self._begin, self._end == other._begin, other._end

    def __ne__(self, other):
        return not self == other

    def __gt__(self, other):
        return other < self


class VirtualPage(object):
    def __init__(self, physical_pages=None):
        self.physcial_pages = sorted(physcial_pages) if physical_pages else []

    def __lt__(self, other):
        if self.physical_pages and other.physical_pages:
            return self.physical_pages[-1].end < other.physical_pages[0].begin

        else:
            raise ValueError

    def __eq__(self, other):
        if self.physical_pages and other.physical_pages:
            return self.physical_pages == other.physical_pages

        else:
            raise ValueError

    def __gt__(self, other):
        return other < self

还有一些观察:

尽管 Python 类中没有“私有”成员之类的东西,但习惯上以一个下划线开头的变量名 ,_表示它不是类 / 模块 / 等的公共接口的一部分。所以,用 '_' 命名公共方法的方法参数似乎不正确,例如def __init__(self, _page_num=-1).

Python 一般不使用 setter/getter;直接使用属性即可。如果需要计算属性值,或者需要其他一些其他处理,请使用@property装饰器(如上面的 PhysicalPage.begin() 所示)。

使用可变对象初始化默认函数参数通常不是一个好主意。 def __init__(self, physical_pages=list())不会每次都用新的空列表初始化physical_pages;相反,它每次都使用相同的列表。如果列表被修改,在下一个函数调用时,physical_pages 将使用修改后的列表进行初始化。请参阅 VirtualPages 初始化程序以获取替代方法。

于 2016-03-20T22:30:03.527 回答