从列表继承的问题

0 python class object

class speciallist(list):

    def __new__(self): 
        return self

    def custommethod(self,param):
         #do stuff
         return value

listesp = speciallist()
listesp.custommethod(param)
Run Code Online (Sandbox Code Playgroud)

我得到"unbound方法custommethod()必须使用speciallist实例作为第一个参数调用"

我以为它会从类中调用该方法,为什么会这样做?

Tho*_*s K 5

这是一个偷偷摸摸的.简短的回答,__new__从您的定义中删除方法.

__new__方法是一个类方法,因此它将而不是实例作为其第一个参数.它旨在创建一个实例(可能是另一个类)并返回它.你只是简单地返回类本身,而不是它的实例.Python允许你custommethod从那里调用,但它没有绑定到实例,所以它不会自动self作为第一个参数插入.

要设置实例,请使用该__init__方法(该方法self作为其第一个参数,但不返回任何内容).