https://qiita.com/ganariya/items/fb3f38c2f4a35d1ee2e8
In order to study Python, I copied a swarm intelligence library called acopy.
In acopy, many interesting Python grammars and idioms are used, and it is summarized that it is convenient among them.
This time, we will make in available for the instance of the class.
__contains__
You can define a special method in your class called __contains__
.
If I define a __contains__
method, does the class contain a certain value ʻitem? Can be simply expressed by the ʻin
operator.
First, let's look at the version without __contains__
.
class A:
def __init__(self, x):
self.arr = list(range(x))
'''
Yes
No
'''
a = A(10)
print(("No", "Yes")[3 in a.arr])
print(("No", "Yes")[23 in a.arr])
This time, define class A and use $ x $ received at initialization.
Creating a list of [0, x)
.
Now, are $ 3,23 $ included in instance a respectively? I'm writing the code [3 in a.arr]
to find out.
Does this include 3 in an array called arr for instance a? You can find out.
However, if the class only looks up such ** inclusion relations **, arr! If there is only one such as, you can write it more intuitively by defining __contains__
.
class A:
def __init__(self, x):
self.arr = list(range(x))
def __contains__(self, item):
return item in self.arr
'''
Yes
No
'''
a = A(10)
print(("No", "Yes")[3 in a])
print(("No", "Yes")[23 in a])
Unlike the previous source code, we have defined the __contains__
method.
Does this method take ʻitem given in ʻitem in instance
as an argument and include this item? You just have to return.
It sounds like a method that isn't very happy, but it can be useful when writing large amounts of code. I still don't know the specific points that I'm happy about ...
Recommended Posts