Generate a first class collection in Python

Introduction

When studying object orientation, I often "The logic that handles multiple objects of the same type is put together in a first class collection." You will see sentences like this. Until now, I didn't know how to write it in python, but I wrote an article because I was able to write in my own way, "If you write this, it will be easier to understand."

I will write it for the time being

Consider a product class and its first class collection (hereinafter referred to as a collection).

import dataclasses
from typing import List

@dataclasses.dataclass(frozen=True)
class Item(object):
    name: str
    price: int

@dataclasses.dataclass(frozen=True)
class ItemCollection(object):
    # default_You can specify what type to initialize in the factory
    items: List[Item] = dataclasses.field(default_factory=list)

    def add_item(self, item):
        #When adding an element, it creates and returns a new object.
        #How to create a new object with added elements without any side effects on an existing collection
        #I couldn't think of anything else ...
        return ItemCollection(self.items + [item])

Please read here for the basic usage of data classes ... (https://qiita.com/madogiwa_429/items/55c78fc6be7887a28df8)

For the time being, you can make a first class collection with this.

Doubts about the first class collection

The reason I used to find it inconvenient for collections There was a comment that "description of processing that should be easy to write becomes troublesome". For example, in this example, when you want to find the total price of the products stored in the collection, How should I write it? If you put it in the list as an int type, you can write it with the sum function, By storing the Item class, it becomes impossible to describe it concisely. Because of this, I didn't know if it was really good to write object-oriented when dealing with arrays.

Use map function

The map function gives a certain solution to this suspicion. The map function handles each element of an iterable object such as a list. Using the map function, the method to find the total price of the products stored in the collection can be written as follows.

@dataclasses.dataclass(frozen=True)
class ItemCollection(object):
    items: List[Item] = dataclasses.field(default_factory=list)

    def add_item(self, item):
        return ItemCollection(self.items + [item])

    def sum_price(self):
        #Instance variable for each element of items"price"Can list only the values of
        price_list = list(map(lambda item: item.price, self.items))
        return sum(price_list)        

Summary

By using the map function, I was able to write the methods of the first class collection concisely. I hope it will be helpful for those who have the same troubles when writing object-oriented programming in Python.

By the way ...

By setting frozen = True, you can certainly prevent reassignment of instance variables, but I couldn't prevent the addition of list elements ...

test = ItemCollection()

#This process results in an error
test.items = ['Tesuto']

#This process does not result in an error and elements are added
test.items.append('Tesuto')

Recommended Posts

Generate a first class collection in Python
Generate a class from a string in Python
case class in python
Class notation in Python
I wrote a class in Python3 and Java
Take a screenshot in Python
Create a data collection bot in Python using Selenium
Generate rounded thumbnails in Python
Create a function in Python
Create a dictionary in Python
A collection of code often used in personal Python
Generate U distribution in Python
Make a bookmarklet in Python
Generate QR code in Python
Image Processing Collection in Python
A collection of Excel operations often used in Python
Draw a heart in Python
Generate 8 * 8 (64) cubes in Blender Python
How to use the __call__ method in a Python class
Developed a library to get Kindle collection list in Python
[MQTT / Python] Implemented a class that does MQTT Pub / Sub in Python
I created a class in Python and tried duck typing
Maybe in a python (original title: Maybe in Python)
Write a binary search in Python
How to write a Python class
[python] Manage functions in a list
First simple regression analysis in Python
Hit a command in Python (Windows)
[Python] Generate QR code in memory
Perform Scala-like collection operations in Python
Landmines hidden in Python class variables
Create a DI Container in Python
Draw a scatterplot matrix in python
ABC166 in Python A ~ C problem
Generate Jupyter notebook ".ipynb" in Python
Write A * (A-star) algorithm in Python
Read PNG chunks in Python (class)
Create a binary file in Python
Solve ABC036 A ~ C in Python
Write a pie chart in Python
Write a vim plugin in Python
Write a depth-first search in Python
[Python] Generate a password with Slackbot
Implementing a simple algorithm in Python 2
Examine the object's class in python
Create a Kubernetes Operator in Python
Solve ABC037 A ~ C in Python
Run a simple algorithm in Python
Draw a CNN diagram in Python
Create a random string in Python
[Python] Inherit a class with class variables
Generate a Python library download badge
The first step in Python Matplotlib
Schedule a Zoom meeting in Python
When writing a program in Python
Create an instance of a predefined class from a string in Python
A class that summarizes frequently used methods in twitter api (python)
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
Create a Python function decorator with Class
[Introduction to Python] How to use class in Python?
Solve ABC175 A, B, C in Python