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

查看:913
本文介绍了从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之外还要做什么。追加(项目)。

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.

一些建议:不要使用键入作为关键字 - type 是一个内置函数。使用 self。前缀访问Python实例变量。因此,请使用 self。< variable name>

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天全站免登陆