How to access data with object ['key'] for your own Python class

How to implement the title, do you think of it? You may be wondering what it is used for in the first place. In my case, I have a column-oriented library that can manipulate data with exactly the same IF as Pandas. I ran into this problem when I tried to make it myself.


#this(↓)How do you implement data access?
df['column_name']

I think that the implementation method like the title is the knowledge required when creating a public library etc. Personally, I was very impressed, so I posted this article.


To get data from your class in the form of object ['key'], you need to define a special method called \ _ \ _ getitem \ _ \ _.


class SampleClass:
    
    def __init__(self):
        self.dict = {'key': 'I got the key.'}
        
    def __getitem__(self, key):
        
        if not isinstance(key, str):
            raise Exception()
                
        return self.dict.get(key)

In the above sample code, SampleClass has dictionary type data (self.dict) in the field, and when SampleClass ['key'] is executed, \ _ \ _ getitem \ _ \ _ is called and it is dictionary type. It is a movement to retrieve the data paired with the key name key in the data.

Execution example



sample = SampleClass()
print(sample['key'])

Conversely, to define the behavior when adding data in the form of object ['key'] to your own class, use the special method \ _ \ _ setitem \ _ \ _.


class SampleClass:
    
    def __init__(self):
        self.dict = {}
        
    def __setitem__(self, key, value):
        
        if not isinstance(key, str):
            raise Exception()
                
        self.dict[key] = value

In the above sample code, \ _ \ _ setitem \ _ \ _ is called when the assignment process for SampleClass ['key'] is executed, and it is specified in the dictionary type data (self.dict) defined in SampleClass. It will be a movement to register the key / value pair.

Execution example



sample = SampleClass()
sample['key'] = 'I got the key.'

In this way, it is possible to give various behaviors to your own class by using special methods. Besides, if you want to define the behavior when using the + operator, for example, you can do it by using the \ _ \ _ add \ _ \ _ method.


class SampleClass:
    
    def __init__(self, in_list):
        self.list = in_list
        
    def __add__(self, other):
        
        if not isinstance(other, SampleClass):
            raise Exception()
                
        return SampleClass([*self.list, *other.list])

In the sample code above, when adding two SampleClass instances (when processed with the + operator), \ _ \ _ add \ _ \ _ is called to combine the list of the two instances (self.list). It will be a movement to create an instance of the new SampleClass.

Execution example



sample1 = SampleClass(['1', '2', '3'])
sample2 = SampleClass(['4', '5'])
sample3 = sample1 + sample2

If you need to consider adding instances of different types, you need to define the \ _ \ _ radd \ _ \ _ method in addition to the \ _ \ _ add \ _ \ _ method. (If the \ _ \ _ add \ _ \ _ method is not defined in the front class when viewed from the + operator, the \ _ \ _ radd \ _ \ _ method of the rear class will work.)


class SampleClass:
    
    def __init__(self, in_list):
        self.list = in_list
        
    def __radd__(self, other):
        
        if not isinstance(other, str):
            raise Exception()
                
        return SampleClass([*self.list, other])

The above sample code defines in the \ _ \ _radd \ _ \ _ method the behavior you would expect if your class (SampleClass) is after the + operator.

Execution example



sample = SampleClass(['1', '2', '3'])
sample2 = '4' + sample

Later, I personally found the \ _ \ _ repr \ _ \ _ method useful. This is a method that defines the character string to be displayed when the instance is called by the print function etc. By defining this, you can avoid the following display (probably everyone has experience).

<__main__.SampleClass object at 0x7f3d06feb3c9>

class SampleClass:
    
    def __init__(self):
        self.list = ['1', '2', '3']
        
    def __repr__(self):
        return '{}'.format(vars(self))

Execution example



sample = SampleClass()
print(sample)

Recommended Posts

How to access data with object ['key'] for your own Python class
[Cloudian # 1] Try to access object storage with AWS SDK for Python (boto3)
python: Use your own class for numpy ndarray
[For recording] Keras image system Part 1: How to create your own data set?
The road to updating Splunkbase with your own Splunk app for Python v2 / v3
[Introduction to Python] How to get the index of data with a for statement
Create your own Big Data in Python for validation
How to scrape image data from flickr with python
How to convert a class object to a dictionary with SQLAlchemy
[Road to intermediate Python] Define in in your own class
Check! How to use Azure Key Vault with Azure SDK for Python! (Measures around authentication)
Python code for writing CSV data to DSX object storage
Try HeloWorld in your own language (with How to & code)
How to write a Python class
[Python] How to FFT mp3 data
Python: How to use async with
How to deal with imbalanced data
How to create your own Transform
How to deal with imbalanced data
How to get started with Python
How to Data Augmentation with PyTorch
How to use FTP with Python
How to calculate date with python
How to access wikipedia from python
[Pandas] I tried to analyze sales data with Python [For beginners]
How to use an external editor for Python development with Grasshopper
[Python] How to get a value with a key other than value with Enum
How to automatically install Chrome Driver for Chrome version with Python + Selenium + Chrome
How to make your own domain site with heroku (free plan)
[Introduction to Python] How to use class in Python?
Memo to ask for KPI with python
[Python] How to make a class iterable
Migrate your own CMS data to WordPress
How to work with BigQuery in Python
Convert FX 1-minute data to 5-minute data with Python
How to do portmanteau test with python
[Python] Organizing how to use for statements
How to display python Japanese with lolipop
To import your own module with jupyter
How to access RDS from Lambda (python)
How to install your own (root) CA
How to use __slots__ in Python class
How to enter Japanese with Python curses
Publish your own Python library with Homebrew
[Python] How to deal with module errors
How to read problem data with paiza
How to install python3 with docker centos
[python] How to add RDF triples to your own Fuseki server using rdflib
How to upload with Heroku, Flask, Python, Git (4)
Try to make your own AWS-SDK with bash
How to create sample CSV data with hypothesis
How to read a CSV file with Python 2/3
How to enjoy programming with Minecraft (Ruby, Python)
[REAPER] How to play with Reascript in Python
[Python] Implement your own list-like class using collections.UserList
Strategy on how to monetize with Python Java
Summary of how to read numerical data with python [CSV, NetCDF, Fortran binary]
[Python] How to draw multiple graphs with Matplotlib
[Python] How to read excel file with pandas
How to crop an image with Python + OpenCV
[Python] How to read data from CIFAR-10 and CIFAR-100