python的__getitme__ 和 __len__ 两个方法

2025-10-23 03:44:16

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__ 两个方法

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢