我想创建一个只能接受某些类型的列表.因此,我试图从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中懒惰地评估列表?
例如
a = 1
list = [a]
print list
#[1]
a = 2
print list
#[1]
Run Code Online (Sandbox Code Playgroud)
如果列表设置为懒惰评估,那么最后一行将是[2]