2013-11-25 19 views
0

这是一个稍微独特的请求。我想看看是否有可能添加额外的功能列表()数据结构,像“追加”我想补充下继承列表的性能提供了新的类名坐标旋转:Python:将新功能添加到列表结构中,使用不同的名称

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

该行代码初始化坐标,但未将'a'定义为值为[1,0,0]的列表。这样的代码执行时。

目前

print a 

>>> a 
[] 

我找

print a 

>>> a 
[1,0,0] 

和附加功能,使得以下为真:

a.double() 
print a 
>>> a 
[2,0,0] 

是否有可能定义一个类的值?这样它可以运载现有的数据结构?

+0

考虑直接继承',而不是'UserList' list'。 – aragaer

回答

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 

或者,如果你有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 

这似乎是个好习惯。您还应该重载其他列表接口方法(如__getitem__)。由于Python中的duck typing,只要它包含所有必要的方法,您的类是否从list派生并不重要。

+0

谢谢,我想我明白了。我现在要弄清楚为什么它使用一个简单的函数,但没有包含Numpy操作在内的大功能。 – CromeX

+0

啊......现在我明白你的意思是复制容器。通过使用'self = blah blah'我重新定义'self',因此它在通话中被忽略。当我保存到self [:] = blah blah'时,我发现它保留了相同的容器。谢谢 – CromeX

+0

@CromeX是的,正好。没问题! – BartoszKP

0

可以继承list类以在list范围内创建自己的自定义函数。你做错了。

这是很简单的比你想象的:

class __VecRot(list): 

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

然后你可以使用它像这样:

>>> a = __VecRot([1,0,0]) 
>>> a 
[1, 0, 0] 
>>> a.double() 
>>> a 
[2, 0, 0] 
>>> a.double() 
>>> a 
[4, 0, 0] 
相关问题