【问题标题】:How to properly create a list subclass that returns a list generated from file in python?如何正确创建一个列表子类,该子类返回从 python 中的文件生成的列表?
【发布时间】:2016-03-13 04:49:13
【问题描述】:

我在子类化方面遇到了一些问题。

我需要创建一个继承列表属性的类,但我需要返回的列表 (self.tiles_pool) 是在构造类时创建的。该列表由外部 CSV 文件生成。我尝试在没有继承的情况下创建类,但很快意识到如果不创建单独的方法就无法返回我的列表。但是我需要类的实例是一个列表对象(即在我打印对象时打印生成的列表)。该课程用于创建一个瓷砖池,就像拼字游戏中的字母瓷砖袋一样。

如果有某种方法可以返回我的列表 (self.tiles_pool) 无需继承和不使用用户定义的方法会更好.

到目前为止,这是我的代码:

import csv
import random


class TilePool(list):
    def __init__(self):
        list.__init__(self)

        # Open csv file
        with open("tiles.csv") as f:
            # Read csv into list of lists of each lines values
            tiles_csv = csv.reader(f, delimiter=",")

            # Convert the list into a tile pool
            self.tiles_pool = [(line[0], line[1])
                               for line in tiles_csv if len(line[0]) == 1
                               for x in xrange(int(line[2]))]

            del tiles_csv

    def pop(self, tile_count=None):
        assert len(self.tiles_pool) > 0, "# Tile Pool is empty"

        if tile_count is None:
            tile_count = 7

        assert tile_count in xrange(1, 8), "# Tile Count must be between 1 and 7"

        new_tiles = []
        counter = 1
        while len(self.tiles_pool) > 0 and counter <= tile_count:
            rand_choice = random.choice(self.tiles_pool)  # Get a random tile
            new_tiles.append(rand_choice)  # Add it to new_tiles list
            self.tiles_pool.remove(rand_choice)  # Delete it from pool

            counter += 1

        return new_tiles

    def view_pool(self):
        if len(self.tiles_pool) == 0:
            print("# Tile Pool is empty")

        else:
            for tile in self.tiles_pool:
                print("{letter}: {score}".format(letter=tile[0], score=tile[1]))

            print len(self.tiles_pool)

我知道这个实现可能看起来很奇怪,我可能只是把它放在一个函数中,但我正在接受指示,让它成为一个类。任何帮助或建议将不胜感激。谢谢。

【问题讨论】:

    标签: python list inheritance return subclassing


    【解决方案1】:

    如果不使用list,为什么要继承它? self 是您想要的列表,无需创建tiles_pool。由于可以使用序列初始化列表,因此延迟父 __init__ 直到您可以将其提供给 csv。你的代码做了一些我不明白的事情,比如复制瓷砖line[2] 次,但我想你知道你在那里做什么。

    在此示例中,我删除了 tiles_pool 以支持使用 self 并进行一些其他调整,例如使用列表的“真实性”(bool([1]) is True 而bool([]) is False)而不是使用len,但它应该和原来的一样工作。

    import csv
    import random
    
    
    class TilePool(list):
        def __init__(self):
            with open("tiles.csv") as f:
                tiles_csv = csv.reader(f, delimiter=",")
                list.__init__(self, (line[0:2]
                               for line in tiles_csv if len(line[0]) == 1
                               for x in xrange(int(line[2]))))
    
    
        def pop(self, tile_count=None):
            # non-empty list is truthy
            assert self, "# Tile Pool is empty"
    
            if tile_count is None:
                tile_count = 7
    
            assert tile_count in range(1, 8), "# Tile Count must be between 1 and 7"
    
            new_tiles = []
            counter = 1
            while self and counter <= tile_count:
                rand_choice = random.choice(self)  # Get a random tile
                new_tiles.append(rand_choice)  # Add it to new_tiles list
                self.remove(rand_choice)  # Delete it from pool
                counter += 1
            return new_tiles
    
        def view_pool(self):
            if not self:
                print("# Tile Pool is empty")
            else:
                for tile in self:
                    print("{letter}: {score}".format(letter=tile[0], score=tile[1]))
                print len(self)
    
    t = TilePool()
    t.pop(3)
    t.view_pool()
    

    【讨论】:

    • 哦,我明白了!行。谢谢,这正是我所需要的。我尝试搜索如何做到这一点,并接近于list.__init__ 部分。我在继承方面工作不多,所以我不确定它的含义。
    • 是的,一开始可能会令人费解。您实现了一个“具有”关系(我的对象有一个列表,所以我需要编写自己的访问器),这是一个“是”关系(我的对象是一个列表,因此现有方法可以使用它)。
    【解决方案2】:

    如果您想避免继承和用户定义的方法,我会利用 python 的 magic 方法来做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多