python的__getitme__ 和 __len__ 两个方法

 时间:2026-02-16 02:20:37

1、我们来定义多个坐标位置,为了定义它我们首先引入  collections 中的namedtuple,自定义一个元组,具备两个坐标参数x,y如下所示

from collections import namedtuple

Point=namedtuple('point',['x','y'])

python的__getitme__ 和 __len__ 两个方法

2、然后我们定义一个坐标类,在里面定义两个x,y轴的参数集合

如下所示:

class MyPoint:    

        px = list(x for x in range(7))  x轴的集合    

        py = list(y for y in 'asdfghj') y轴的集合

python的__getitme__ 和 __len__ 两个方法

3、定义一个类的__init__方法,也就是初始化该类的方法

from collections import namedtuple

Point=namedtuple('point',['x','y'])

class MyPoint:    

     px = list(x for x in range(7))   

    py = list(y for y in 'asdfghj')    

    def __init__(self): # 定义方法        

        self._mypoint=list(Point[x,y] for x in self.px for y in self.py)

python的__getitme__ 和 __len__ 两个方法

4、接着我们在定义一个 __len__,获取长度的方法

def __len__(self): #定义的方法   

       return len(self._mypoint)

python的__getitme__ 和 __len__ 两个方法

5、最后我们在定义一个__getitem__,迭代对象的方法

def __getitem__(self, item):    

        return self._mypoint[item]

python的__getitme__ 和 __len__ 两个方法

6、下面我们开始来使用这个类,然后看看 __getitme__  __len__ 这两个方法

spoint = MyPoint()

len(spoint)

调用方法发现报错

File "C:/Users/king/PycharmProjects/baidu/blog/tests.py", line 49, in <genexpr>

    self._mypoint = list(Point[x,y] for y in self.pys for x in self.pxs)

TypeError: 'type' object has no attribute '__getitem__'

是因为 Point调用错误list(Point[x,y] for y in self.pys for x in self.pxs)改为

list(Point(x,y) for y in self.pys for x in self.pxs)

调用时候要和上面定义的中括号区别开

修改后代码如下图

python的__getitme__ 和 __len__ 两个方法

7、修改后我们调用看看

spoint = MyPoint()print len(spoint)

输出49

根据位置输出坐标:

print spoint[8]print(spoint[7])

输出结果:

Point(x=1, y='s')

Point(x=0, y='s')

python的__getitme__ 和 __len__ 两个方法

  • word简体字转换繁体字
  • 浙江旅游攻略
  • word2013中如何预先自定义内容的格式
  • PPT2016中怎样将幻灯片方向设置为纵向?
  • 穿越寻宝记宝芝林无影脚秘籍如何获取?
  • 热门搜索
    维生素b6的作用及功能 uncle什么意思 eva是什么材料 一次什么的尝试作文 xml是什么 什么是共济失调 栩栩如生的意思是什么 广场舞你牛什么牛 古文运动 thick什么意思