|
楼主 |
发表于 2017-8-23 16:07:42
|
显示全部楼层
我用另外的方面实现了这个功能,可能不是最好的实现方法。
- #定制序列,进阶版
- #super的使用,摒弃前一版的字典
- class CountList( list ):
- def __init__( self, *args ):
- super().__init__( args )
- self.count = []
- for i in args:
- self.count.append( 0 )
- def __len__(self):
- return len( self.count )
-
- def __getitem__( self, key ):
- #可以实现切片访问
- if isinstance( key, slice ):
- _begin = 0 if key.start == None else key.start
- _end = len( self.count ) if key.stop == None else key.stop
- _step = 1 if key.step == None else key.step
- for _index in range( _begin, _end, _step ):
- self.count[ _index ] += 1
- return super().__getitem__( key )
- else:
- self.count[ key ] += 1
- return super().__getitem__( key )
-
- def __setitem__( self, key, value ):
- self.count[ key ] += 1
- super().__setitem__( key, value )
-
- def __delitem__( self, key ):
- del self.count[ key ]
- super().__delitem__( key )
-
- def append( self, value ):
- self.count.append( 0 )
- super().append( value )
-
- def pop( self ):
- self.count.pop()
- return super().pop( )
-
- def remove( self, value ):
- key = super().index( value )
- del self.count[ key ]
- super().remove( value )
-
- def insert( self, key, value ):
- self.count.insert( key, 0 )
- super().insert( key, value )
-
- def clear( self ):
- self.count.clear()
- super().clear()
-
- def reverse( self ):
- self.count.reverse()
- super().reverse()
复制代码
参考链接:python魔法方法-自定义序列 |
|