返回顶部

收藏

python重写父类方法

更多
class MyList:
    def __init__(self, start):
        #self.wrapped = start[:]                
        self.wrapped = []                       
        for x in start: self.wrapped.append(x)
    def __add__(self, other):
        return MyList(self.wrapped + other)
    def __mul__(self, time):
        return MyList(self.wrapped * time)
    def __getitem__(self, offset):
        return self.wrapped[offset]
    def __len__(self):
        return len(self.wrapped)
    def __getslice__(self, low, high):
        return MyList(self.wrapped[low:high])
    def append(self, node):
        self.wrapped.append(node)
    def __getattr__(self, name):                
        return getattr(self.wrapped, name)
    def __repr__(self):
        return 'self.wrapped'

class MyListSub(MyList):
    calls = 0                                  

    def __init__(self, start):
        self.adds = 0                          
        MyList.__init__(self, start)

    def __add__(self, other):
        MyListSub.calls = MyListSub.calls + 1  
        self.adds = self.adds + 1              
        return MyList.__add__(self, other)

    def stats(self):
        return self.calls, self.adds           

if __name__ == '__main__':
    x = MyListSub('A')
    y = MyListSub('B')
    print x[0]
    print x[1:]
    print x + ['C']
    print x + ['D']
    print y + ['E']
    print x.stats()

标签:Python,Class

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. 博主 发表 2013-01-28 15:43:29 How to compile Python code to Java .class
  2. Kevin Shao 发表 2014-05-12 11:58:48 Python高级特性 Part III: Classes和Metaclasses
  3. 博主 发表 2013-11-23 08:00:00 Python class 入门
  4. 博主 发表 2013-01-28 15:43:29 How to compile Python code to Java .class
  5. fanhuafeng 发表 2014-03-12 08:41:55 python学习之类(class)
  6. Jeffrey4l 发表 2015-01-07 16:00:00 PIP install from local
  7. YCFlame 发表 2013-05-09 12:58:43 语不惊人死不休
  8. amaozhao@gmail.com ( 发表 2015-01-29 02:13:01 python lambda教程
  9. jasine 发表 2014-12-13 13:38:59 Python学习笔记
  10. 吴遥 发表 2014-03-27 07:42:00 python读文件性能测试
  11. 博主 发表 2014-02-23 07:35:24 如何安装包到指定版本的python
  12. 博主 发表 2014-12-11 06:42:34 导出骑记(iriding.cc)轨迹

发表评论