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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值