python contains_如何在python中设置__contains__方法?

I'm having trouble understanding how to properly set up a contains method in my class. I know it automatically uses the operator "in" when you call it, i just don't think I understand how to set it up correctly.

I have to use it to see if anotherCircle is contained within a specific circle (both input from the user). The prof had us do two different types of methods for this.

The first one I have no problems with and more or less understand what it is doing, It is as follows:

def contains(self, circle2d):

dist = math.sqrt((circle2d._x - self._x)**2 + (circle2d._y - self._y)**2) #Distance of second circle's coords from the first circle's coords

if dist + circle2d._radius <= self._radius:

return True

However, the next method, which is supposed to do the same thing, uses the contains method so that we can call it with in in the main function. All I have is this:

def __contains__(self, anotherCircle):

if anotherCircle in self:

return True

I get multiple errors when I try to run this. I think i'm missing something on self, but I'm not sure what? Could someone please try to explain to me what exactly you need to do when you're writing a contains method such as this?

解决方案

The __contains__ method on an object doesn't call in; rather, it is what the in operator calls.

When you write

if circle1 in circle2:

The python interpreter will see that circle2 is a Circle object, and will look for a __contains__ method defined for it. It will essentially try to call

circle2.__contains__(circle1)

This means that you need to write your __contains__ method without using in, or else you will be writing a recursive method that never ends.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值