[Road to intermediate Python] Define in in your own class

Link to summary

https://qiita.com/ganariya/items/fb3f38c2f4a35d1ee2e8

Introduction

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.

Concrete example

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.

Finally

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

[Road to intermediate Python] Define in in your own class
[Road to Python Intermediate] Define __getattr__ function in class
How to define your own target in Sage
A road to intermediate Python
Try to improve your own intro quiz in Python
[Road to Intermediate] Understanding Python Properties
[Road to intermediate Python] Install packages in bulk with pip
[Road to intermediate Python] Use if statement in list comprehension
[Road to intermediate Python] Use ternary operators
[Road to Python Intermediate] Call a class instance like a function with __call__
How to dynamically define variables in Python
[LLDB] Create your own command in Python
Easily use your own functions in Python
Create your own graph structure class and its drawing in python
How to use __slots__ in Python class
[Road to intermediate Python] Use lambda expressions
Get your own IP address in Python
Specify your own class in class argument and return type annotation in Python
[Road to intermediate Python] Article link summary
How to access data with object ['key'] for your own Python class
[Python] Implement your own list-like class using collections.UserList
Import your own modules in Grasshopper's Python development
python: Use your own class for numpy ndarray
case class in python
Class notation in Python
The road to updating Splunkbase with your own Splunk app for Python v2 / v3
Memo to create your own Box with Pepper's Python
Create your own Big Data in Python for validation
[Introduction to Udemy Python 3 + Application] 66. Creating your own exceptions
Create your own Random Dot Stereogram (RDS) in Python.
Use the CASA Toolkit in your own Python environment
Try to put LED in your own PC (slightly)
Convert / return class object to JSON format in Python
To flush stdout in Python
Login to website in Python
Speech to speech in python [text to speech]
How to develop in Python
Post to Slack in Python
How to use the __call__ method in a Python class
Try sorting your own objects with priority queue in Python
How to use pyenv and pyenv-virtualenv in your own way
How to define multiple variables in a python for statement
[Road to intermediate Python] Enables comparison operations with original classes
Try HeloWorld in your own language (with How to & code)
[Python] When you want to import and use your own package in the upper directory
How to write a Python class
[Python] How to do PCA in Python
[Python] Make your own LINE bot
Convert markdown to PDF in Python
Landmines hidden in Python class variables
[Road to Python intermediate] Dynamically specify execution method by variable name
How to use SQLite in Python
How to create your own Transform
Read PNG chunks in Python (class)
In the python command python points to python3.8
Try to calculate Trace in Python
Road to Linux Intermediate: Network Edition
How to use Mysql in python
Try to log in to Netflix automatically using python on your PC
How to wrap C in Python
How to use ChemSpider in Python