python的__getitme__ 和 __len__ 两个方法

时间:2024-10-13 12:20:26

1、我们来定义多个坐标位置,为了定义它我们首先引入collections中的namedtuple,自定义一个元组,具备两个坐标参数x,y如下所示from collections import namedtuplePoint=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 namedtuplePoint=na罪焐芡拂medtuple('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()le荏鱿胫协n(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__ 两个方法
© 手抄报圈