从 Python 列表继承后覆盖 append 方法 [英] Overriding append method after inheriting from a Python List

查看:31
本文介绍了从 Python 列表继承后覆盖 append 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个只能接受某些类型的列表.因此,我试图从 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)

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

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).

我应该怎么做?

推荐答案

我对您的课程进行了一些更改.这似乎有效.

I have made some changes to your class. This seems to be working.

一些建议:不要使用 type 作为关键字 - type 是一个内置函数.Python 实例变量使用 self. 前缀访问.所以使用 self..

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.<variable name>.

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 "<pyshell#25>", line 1, in <module>
    tl.append(None)
  File "<pyshell#22>", line 7, in append
    raise TypeError, 'item is not of type %s' % self.type
TypeError: item is not of type <type 'str'>

这篇关于从 Python 列表继承后覆盖 append 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆