I want to create a list that can only accept certain types. As such, I'm trying to inherit from a list in Python, and overriding the append() method like so:
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)
This will of cause an infinite loop because the body of append() calls itself, but I'm not sure what to do other than using self.append(item).
How I should go about doing this?
解决方案
I have made some changes to your class. This seems to be working.
A couple of suggestions: don't use type as a keyword - type is a built in function. Python instance variables are accessed using the self. prefix. So use self..
class TypedList(list):
def __init__(self, type):
self.type = type
def append(self, item):
if not isinstance(item, self.type):
raise TypeError, 'item is not of type %s' % self.type
super(TypedList, self).append(item) #append the item to itself (the list)
from types import *
tl = TypedList(StringType)
tl.append('abc')
tl.append(None)
Traceback (most recent call last):
File "", line 1, in
tl.append(None)
File "", line 7, in append
raise TypeError, 'item is not of type %s' % self.type
TypeError: item is not of type