相关疑难解决方法(0)

从Python列表继承后覆盖append方法

我想创建一个只能接受某些类型的列表.因此,我试图从Python中的列表继承,并覆盖append()方法,如下所示:

class TypedList(list):
    def __init__(self, type):
        self.type = type

    def append(item)
        if not isinstance(item, type):
            raise TypeError, 'item is not of type %s' % type
        self.append(item)  #append the item to itself (the list)
Run Code Online (Sandbox Code Playgroud)

这将导致无限循环,因为append()的主体调用自身,但我不知道除了使用self.append(item)之外还要做什么.

我该怎么做呢?

python inheritance list

13
推荐指数
4
解决办法
2万
查看次数

Python,懒惰列表

是否有可能在Python中懒惰地评估列表?

例如

a = 1
list = [a]
print list
#[1]
a = 2
print list
#[1]
Run Code Online (Sandbox Code Playgroud)

如果列表设置为懒惰评估,那么最后一行将是[2]

python lazy-evaluation

9
推荐指数
3
解决办法
7643
查看次数

标签 统计

python ×2

inheritance ×1

lazy-evaluation ×1

list ×1