【发布时间】: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