Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : Difference between static methods vs class method [duplicate]

Tags:

python

oop

Possible Duplicate:
What is the difference between @staticmethod and @classmethod in Python?

  • I am learning OOP in python and came to know about these two methods
  • It seems that the difference in terms of syntax is that class methods are implicitly passed the class they belong to as their first parameter
class Circle:
  all_circles = [] # class variable

  @staticmethod
  def total_area():
      for c in Circle.all_circles: # hardcode class name
          # do somethig

  @classmethod
  def total_area(cls):
      for c in cls.all_circles: # no hardcode class name
          # do something

I see class method as more flexible since we don't hardcode the class

Question:
- Is it even a question which one is better? @staticmethod or @classmethod?
- what are the scenarios suitable to use of each one of these methods?

like image 560
daydreamer Avatar asked Mar 16 '12 20:03

daydreamer


1 Answers

A classmethod gets passed the class 'cls' that it was called upon. For more details see: What is the difference between @staticmethod and @classmethod in Python?

like image 122
Sid Avatar answered Nov 11 '22 20:11

Sid