0

I am setting up a python class and I have 2 ways to go about it:

  1. Create a class and all methods as class methods. When calling the methods on my main block, it would be cls.methodName()

e.g.

class demoClass():
    
    @classmethod
    methodA(cls):
        print('Method A')

Calling from main

demoClass.methodA()
demoClass.methodA()
demoClass.methodA()
  1. Create a class and all methods are object methods and require an instance of the class to call them.

e.g.

class demoClass():
    
    methodA(self):
        print('Method A')

Calling from main

demoObj = demoClass()
demoObj.methodA()
demoObj.methodA()
demoObj.methodA()

I want know which way would be better. I am more inclined towards using Object level methods because this class will be used across a lot of parts of the main code for different scenarios and require different setup for each scenario hence setting up the objects specific to each use case would make sense

My major point of concern is performance and memory usage Between the 2 approaches, which would be better in terms of just performance and memory usage (disregard the use case)?

  • Does this answer your question? [What's an example use case for a Python classmethod?](https://stackoverflow.com/questions/5738470/whats-an-example-use-case-for-a-python-classmethod) – Marcus Müller Oct 14 '21 at 23:27
  • There's no "better", there's an "appropriate for what it does". You need to understand *why* you'd want a classmethod or an instance method. In reality, you simply never encounter a situation where you can't tell which one you need. – Marcus Müller Oct 14 '21 at 23:28
  • If you don't need any local state, then a class is just a way to organize functions, although a module might be a better choice. As soon as you need local state, then of course you need object methods. – Tim Roberts Oct 14 '21 at 23:44
  • The choice here would be between *static* methods and instance methods (with static methods being the right choice, if you are going to define a class at all, which is a big "if" IMO). Class methods are typically used to implement alternative constructors (receiving a class argument so that it can be instantiated). – chepner Oct 15 '21 at 00:23

0 Answers0