Python: Static Method & Instance Methods

23 Views Asked by At

I'm fairly new to programming and have been taking this online python course. I started reading up about class methods, static methods, & instance methods. From my understanding, static methods are those that take in objects as parameters and that they don't modify objects etc.

Question 1: Does it make the code more efficient if you declare it using '@staticmethod' above the decleration? What's the point of neccessarily doing it? I don't see the difference it would make in code. Essentially, what effects would leaving an undeclared static method have on the code.

Question 2: What exactly is a class method. I understand the special perameter it takes is 'cls'. But when should you declare a method as '@classmethod'? And why? What changes in the code if don't explicitly declare a method to be a class method.

Sorry about the easy question! I'm pretty new to programming and couldn't really find an answer I can understand. If there's a flaw in the way I'm thinking about it, please let me know!

I've posted an example below that contains both.

from typing import ClassVar
from dataclasses import dataclass, field

@dataclass
class Rectangle:
  """ example of class and static methods/functions """   
  # class ("static") intended constants
  
  ORIGINAL_DEFAULT_DIMENSION:ClassVar[int] = 1.
    
    # class attribute that will change over time
  default_dimension:ClassVar[int] = ORIGINAL_DEFAULT_DIMENSION
  
  
  #instance variables
  height: float = field(default = 0.0)
  width: float = field(default = 0.0)

  #getter
  def get_area(self) -> float:
    return self.height * self.width 

  #setter 
  def set_width_height(self, width:float, hi:float) -> bool:
      self.width = width
      self.height = hi
      return True

  @classmethod
  def set_default_dim(cls, new_dimension) -> bool:
      cls.default_dimension = new_dimension
      return True

  @staticmethod
  def which_is_bigger( rect_1, rect_2 ) -> object:
  """ takes two Rectangle objects and 
      returns a Rectangle reference to the one with
      the larger area. """

      if rect_1.get_area() > rect_2.get_area():
          return rect_1
      else:
          return rect_2 
1

There are 1 best solutions below

0
Tathya Garg On

Static methods are like any other function outside the class. The only reason that you might encounter it would be for better organization. Code just sometimes looks better, bunched together neatly in a class.

As for class methods, they're often used to execute some code before an object is initialized. Consider this code for example:

fp = 'hello.txt'
fp2 = 'world.docx'

class FileManipulator:
    def __init__(self, data):
        # Let's say, in this example, the data is a list of strings.
        ...

    @classmethod
    def from_txt(cls, fp):
        # This could return an object with data loaded as the text from a txt file.
        return cls(data=processed_data)

    @classmethod
    def from_docx(cls, fp):
        # same thing here
        return cls(data=processed_data)