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."
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.
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.
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)
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 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