zoukankan      html  css  js  c++  java
  • Python面向对象进阶示例--自定义数据类型

    需求:

    基于授权定制自己的列表类型,要求定制的自己的__init__方法,
    定制自己的append:只能向列表加入字符串类型的值
    定制显示列表中间那个值的属性(提示:property)
    其余方法都使用list默认的(提示:__getattr__加反射)

     1 class List:
     2     def __init__(self,value):
     3         self.x=list(value)
     4     def append(self,value):
     5         if not isinstance(value,str):
     6             raise TypeError('append到列表的内的元素必须是str类型')
     7         self.x.append(value)
     8     def insert(self,index,value):
     9         self.x.insert(index,value)
    10     def __getattr__(self, item):
    11         return getattr(self.x,item)
    12 
    13     @property
    14     def type(self):
    15         print(self.x)
    16         t=int(len(self.x)/2)
    17         print(self.x[t],type(self.x[t]))
    18 
    19 
    20 l=List([1,2,3])
    21 l.append("egon")
    22 l.append('hello')
    23 l.append('alex')
    24 l.insert(7,5)
    25 l.pop()
    26 l.type
  • 相关阅读:
    时间工厂[XDU1013]
    奇妙的旅行[XDU1012]
    金子上的友情[XDU1011]
    素数环问题[XDU1010]
    转盘游戏[XDU1006]
    跳舞毯[XDU1005]
    Tri Tiling[HDU1143]
    A Walk Through the Forest[HDU1142]
    核反应堆[HDU2085]
    How Many Trees?[HDU1130]
  • 原文地址:https://www.cnblogs.com/baomanji/p/6757582.html
Copyright © 2011-2022 走看看