将对象附加到列表

时间:2014-02-01 19:06:12

标签: python

我正在尝试将给定值(金额)中的对象追加到列表中。但是我现在所遇到的问题是Coin对象不能被解释为整数。 add_to_table方法是否有解决方法以实现预期目标?

class Test:

    def __init__(self, table=[]):
        """(Test, int) -> NoneType
        """
        self.table = [(0, []), (1, []), (2, [])]

    def add_to_table(self, amount):
        """(Test, int) -> NoneType

        Adds to the first table Coin(amount) to Coin(1)

        ex.

        [(0, [Coin(3), Coin(2), Coin(1)]), (1, []), (2, [])]

        """
        self.table[0][1].extend(reversed(range(Coin(1), Coin(amount + 1))))

class Coin:

    def __init__(self, length):
        """(Coin, int) -> NoneType
        """
        self.length = length

预期产出:

t1 = Test()
t1.table
[(0, []), (1, []), (2, [])]
t1.add_to_table(3)
t1.table
[(0, [Coin(3), Coin(2), Coin(1)]), (1, []), (2, [])]

3 个答案:

答案 0 :(得分:2)

为了得到你想要的东西,有必要进行两项改变:

class Test:

    def __init__(self, table=[]):
        """(Test, int) -> NoneType
        """
        self.table = [(0, []), (1, []), (2, [])]

    def add_to_table(self, amount):
        """(Test, int) -> NoneType

        Adds to the first table Coin(amount) to Coin(1)

        ex.

        [(0, [Coin(3), Coin(2), Coin(1)]), (1, []), (2, [])]

        """
        self.table[0][1].extend([Coin(n) for n in range(amount, 0, -1)])

class Coin:

    def __init__(self, length):
        """(Coin, int) -> NoneType
        """
        self.length = length

    def __repr__(self):
        return 'Coin(%s)' % (self.length,)

第一个变化是,为了生成Coin的值范围,上面的add_to_table方法使用列表推导:[Coin(n) for n in range(amount, 0, -1)]。第二个更改是因为您希望Coin列表显示为[Coin(3), Coin(2), Coin(1)]。方法__repr__控制类的显示方式。因此,此方法已添加到Coin。有了这两个变化,上面的结果就是:

>>> t1 = Test()
>>> t1.table
[(0, []), (1, []), (2, [])]
>>> t1.add_to_table(3)
>>> t1.table
[(0, [Coin(3), Coin(2), Coin(1)]), (1, []), (2, [])]

答案 1 :(得分:0)

试试这个:

def add_to_table(self, amount):
    for i in range(amount, 0, -1):
        self.table[0][1].append(Coin(i))

答案 2 :(得分:0)

如果您希望表具有实际的Coin对象或对象的值,则不清楚。在这里,我假设它的价值。

您需要一个返回Coin个对象值的方法。如果您只是将它们添加到列表中,则使用对象的特殊表示(由__repr__方法返回):

>>> class Foo(object):
...     pass
... 
>>> [Foo(),Foo()]
[<__main__.Foo object at 0x20b44d0>, <__main__.Foo object at 0x20b4510>]
>>> class Foo(object):
...     def __repr__(self):
...         return "I am a Foo object"
... 
>>> [Foo(), Foo()]
[I am a Foo object, I am a Foo object]

但是,__repr__方法应该用于返回对象的字符串表示,而不是用于返回有意义的值,换句话说,它不是解决方案。

您需要在Coin中使用方法返回硬币的值,然后在将其传递给Table时使用该值:

class Coin(object):
    ''' A coin object with a length '''

    def __init__(self, length):
        self._length = length

    @property
    def length(self):
        return self._length

现在,你需要这样做:

coins = [Coin(1), Coin(2)]
table = Test()
for coin in coins:
    table.add_to_table(coin.length)

我正在使用@property decorator让生活更轻松。

你仍然需要确保硬币是用整数而不是字符串创建的,换句话说,Coin('1')将完全正常,但你的add_to_table方法会引发异常。

相关问题