Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python When to OOP and When Not to OOP

I have a simple best practice question rather than a technical / "how do I?" Question related to object oriented programming in Python.

I've recently been working on some OOP Python code that reads in data and stores them in a bespoke class. It's too detailed to post all the code here so I'll make a very simple example using cakes.

My main class - cake - looks something like the below and stores various data attributes about each 'cake'. Some variables are strings e.g. name while others are integers or floats e.g. layers.

class cake():

    def __init__(self, name, layers, icing):
        self.name = name
        self.layers = layers
        self.icing = icing

A large number of these objects are created when the data is read in, all of which are stored in a list:

cakebox = []
cakebox.append(cake("chocolate", 2, "Y"))
cakebox.append(cake("chocolate", 3, "Y"))
cakebox.append(cake("chocolate", 2, "N"))
cakebox.append(cake("lemon", 3, "Y"))
cakebox.append(cake("jamsponge", 2, "N"))
cakebox.append(cake("fruit", 1, "N"))

.........etc

The idea behind the 'cakebox' list is to act like simple 'database' from which results can be drawn. This is easily done using list comprehensions such as

icingcakes = [x for x in cakebox if x.icing == "Y"]

But some operations I'm finding I'm doing again and again, for example get all unique cake names:

uniquecakenames = list(set([x.name for x in cakebox]))

Given I use this code (or similar) several times would I be better making 'cakebox' a class with this code as a method, perhaps using 'list' as a super class, or am I over complicating things by creating a cakebox class in this example?

Please note that the real code is more complicated than my rather simplified cake example....! Also I've just typed this example on my iPad so please forgive me if there are minor code mistakes - hopefully it's enough to get across the main points.

All comments or suggestions welcome

like image 264
Mark Avatar asked Dec 02 '25 14:12

Mark


1 Answers

If your model includes something called a cakebox and that entity has properties and functionality that are themselves described (and named) in your model, and if that functionality is used in more than one place and -- especially -- if it is likely to be refactored in the future you would be well advised to encapsulate the entity in a class from the outset of your project. You can begin with a simple implementation as appropriate but your code will increase in legibility immediately and refactoring in the future will be much simpler.

like image 167
Larry Lustig Avatar answered Dec 04 '25 06:12

Larry Lustig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!