DEV Community

30 Days of Python 👨‍💻 - Day 8 - OOP Basics

Arindam Dawn on June 28, 2020

Python is a multi-paradigm language. That's a cool-sounding term! Coming from the JavaScript universe, I am aware of this as JavaScript is a multi-...
Collapse
 
petrtcoi profile image
Petr Tcoi

Hello. What is the difference between common function and classmethod?

def foo(self)

vs

@classmethod
def foo(cls)

?

When I should prefer one over another?

Thanks

Collapse
 
arindamdawn profile image
Arindam Dawn

Hey Peter,
Thanks for your question.

Well, a generic function is just a block of code that can be reused in your codebase. You can, for example, have a utility function dasherize which replaces spaces in words with a hyphen like this,

def dasherize(word):
  return word.replace(' ', '-')

print(dasherize("Hello Friend")) #Hello-Friend 

This you can reuse anywhere in your code.

Now class methods are a member of a class that you have defined. For example, you have a class called Vehicle and you have a class method named turnLeft().
You will be using this class method when you have to work with a vehicle object.

This is just a very basic explanation. There is no preference as such but depends on how you have structured your code and what you are trying to do.

Hope it helps!

Collapse
 
petrtcoi profile image
Petr Tcoi

Thank you

But I mean the difference between class method and class method with @classmethod

Thread Thread
 
arindamdawn profile image
Arindam Dawn

Oops, I probably misunderstood your question then!

Ok let me try to explain the difference:

Here is a class with a simple method

class Avenger:
  def __init__(self, name, weapon):
    self.name = name
    self.weapon = weapon

  def fight(self):
    print(self.weapon)

  @classmethod
  def showOrganization(cls):
    print('MARVEL INC')

spiderman = Avenger('Spiderman', 'dispatch a web')

spiderman.fight() # dispatch a web

Avenger.showOrganization() # this works
spiderman.showOrganization() # this also works

Here what I am trying to show is you can know the Avenger's organization name by simply calling the class method. You can also create an avenger and then get the name of the organization from that avenger but hope you understand the difference!

Thread Thread
 
petrtcoi profile image
Petr Tcoi

Great thank you for the example!

Collapse
 
dsdorazio profile image
Dan

I think you meant to decorate the multiply method with @staticmethod in your final example. :)

Collapse
 
arindamdawn profile image
Arindam Dawn

Thanks Dan. I have updated it now :)

Collapse
 
360observe profile image
$ikind@r

It is very clear to understand for beginners.
Thank You Dawn.

Collapse
 
arindamdawn profile image
Arindam Dawn

I'm glad that you found it useful :)

Collapse
 
jabarny profile image
Javier

My God, I have been looking for a great explanation like this on Classes, properties. Thank you!

Collapse
 
arindamdawn profile image
Arindam Dawn

I am glad you found it useful 😊