1

我有两个班级PairSequence. 一个Pair对象有两个属性,位置和值。Sequence对象是对象的序列Pair

class Pair():
    def __init__(self, position, value):
        self.position = position
        self.value = value
        self.pair = (position, value)

    def __repr__(self):
        return "< Position: {0}, Value: {1} >".format(self.position, self.value)

class Sequence(Pair):
    def __init__(self, pairs):
        self.pairs = pairs
        self.cseg = [pair.value for pair in pairs]
        self.positions = [pair.position for pair in pairs]

    def __repr__(self):
        return "< Seq. {0} >".format(" ".join([str(x) for x in self.cseg]))

我可以Sequence用这个创建一个对象:

>>> Sequence([Pair(0, 2), Pair(2, 8), Pair(3, 1))
< Seq. 2 8 1 >
>>> Sequence.pairs
[< Position: 0, Value: 2 >,
 < Position: 2, Value: 8 >,
 < Position: 3, Value: 1 >]

如何创建一个只给出值列表的Sequence对象,如下面的代码?Pair在这种情况下,Pair位置必须是从 0 到 n - 1 的序列,其中 n 是 的长度Sequence

>>> Sequence([2, 8, 1])
< Seq. 2 8 1 >
>>> Sequence.pairs
[< Position: 0, Value: 2 >,
 < Position: 1, Value: 8 >,
 < Position: 2, Value: 1 >]

我尝试使用此版本的Sequence,但没有用。我收到了这个错误:

AttributeError: 'int' object has no attribute 'value'

class Sequence(Pair):
    def __init__(self, pairs):

        if not isinstance(pairs[0], Pair):
            self = Sequence([Pair(pos, val) for pos, val in enumerate(pairs)])

        self.pairs = pairs
        self.cseg = [pair.value for pair in pairs]
        self.positions = [pair.position for pair in pairs]

    def __repr__(self):
        return "< Seq. {0} >".format(" ".join([str(x) for x in self.cseg]))
4

1 回答 1

4

Pair当您传入包含非对象的列表时,以下将创建一个对象列表Pair,否则它将简单地将给定的Pair对象列表分配给self.pairs

class Sequence(Pair):
    def __init__(self, pairs):
        if not isinstance(pairs[0], Pair):
            self.pairs = [Pair(pos, val) for pos, val in enumerate(pairs)]
        else:
            self.pairs = pairs
        self.cseg = [pair.value for pair in self.pairs]
        self.positions = [pair.position for pair in self.pairs]

您收到错误的原因是,尽管您检查了 的内容,但pairs您仍将其分配给self.pairs

class Sequence(Pair):
    def __init__(self, pairs):
        # the following code will run when you're passing a list of integers
        if not isinstance(pairs[0], Pair):
            self = Sequence([Pair(pos, val) for pos, val in enumerate(pairs)])
        # but the next line will also run
        # which means self.pairs` is now a list of integers
        self.pairs = pairs
        # and that means pair in the following line is an int, not a Pair:
        self.cseg = [pair.value for pair in pairs]
        self.positions = [pair.position for pair in pairs]

最后,您不应该在构造函数中执行以下操作(分配给self):

self = Sequence([Pair(pos, val) for pos, val in enumerate(pairs)])

您正在尝试“覆盖”或“替换”该对象self,但这意味着您正在. 在这种情况下这是不必要的,因为您可以在同一个构造函数中处理这两种情况。反过来,这会导致代码更简洁。SequenceSequence

于 2012-07-02T19:12:21.023 回答