Python:以不同的名称将新函数添加到列表结构中

Cro*_*meX 0 python class list

这是一个稍微独特的请求.我想看看是否有可能在list()数据结构中添加额外的函数,比如'append'我想在一个继承了list属性的新类名下添加坐标旋转:

class __VecRot(list):

    def __init__(self, coords):
        self.coords = coords
        print coords        

    def double(self):
        self.coords = [i*2 for i in self.coords]

a = __VecRot([1,0,0])
Run Code Online (Sandbox Code Playgroud)

该行代码初始化坐标,但它没有将'a'定义为值为[1,0,0]的列表.这样当执行此代码时.

目前

print a

>>> a
[]
Run Code Online (Sandbox Code Playgroud)

我在寻找

print a

>>> a
[1,0,0]
Run Code Online (Sandbox Code Playgroud)

和其他功能,以下是真实的:

a.double()
print a
>>> a
[2,0,0]
Run Code Online (Sandbox Code Playgroud)

是否可以将类定义为值?这样它可以承载现有的数据结构吗?

Bar*_*zKP 5

你正在复制实际的容器.如果你从list你那里获得了存储空间.考虑一下:

 class __VecRot(list):

     def __init__(self, coords):
         list.__init__(self, coords)

     def double(self):
         for i in range(len(self)):
             self[i] = self[i] * 2

 a = __VecRot([1,0,0])

 a.double()

 print a
Run Code Online (Sandbox Code Playgroud)

或者,coords无论如何你都有这个领域,你不需要派生自list:

 class __VecRot:

     def __init__(self, coords):
         self.coords = coords

     def double(self):
         self.coords = [i*2 for i in self.coords]

     def __len__(self):
         return len(self.coords)

     def __str__(self):
         return "__VecRot["+str(self.coords)+"]"

     def __repr__(self):
         return "__VecRot("+repr(self.coords)+")"

 a = __VecRot([1,0,0])

 a.double()

 print a
Run Code Online (Sandbox Code Playgroud)

这似乎是一种更好的做法.您还应该重载其他列表接口方法(如__getitem__).因为在Python中输入duck,所以list只要它包含所有必需的方法,你的类是否派生出来并不重要.