Python classes and objects

what is a class?

  • Class is a template for an object
  • Class should follow camel case notation
  • All classes in one file - when classes are short
  • One class per file - when classes are long

when to use a class?

  • Several functions with share state
  • More than one copy of the same state variables
  • To extend the behavior of an existing functionality
  • Do not use classes for simple things

class - syntax

  • To create a class, use the keyword class
  • Let's looke at the below class
class Calculator:
  pi = 3.14
  def add(self, num1, num2):
    return num1 + num2

  def sub(self, num1, num2):
    return num1 - num2
  • In above class Calculator is the name of the class
  • add, sub are instance methods
  • pi is a class attribute

create object using class

  • Let's use the above class and create an object
calc = Calculator()
print(calc.sum(1, 2))
# output: 3
print(calc.pi)
# output: 3.14
  • Calculator() creates the class object and stores it in variable calc
  • calc.pi will retrieve the value of the attribute
  • calc.sum(1, 2) calls the class method sum with arguments 1 and 2
  • For instance methods self is automatically passed as a default argument.
  • self is nothing but the object itself. i.e self and calc both are same in above code.

__new__ - constructor

  • __new__ is an object constructor
  • By overriding this method we can modify the behaviour of the class/object.
  • Let's see an example
class Person:
  def __new__(cls, *args, **kwargs):
    print("__new__ called")
    instance = super().__new__(cls, *args, **kwargs)
    instance.developer = "Anjaneyulu Batta"
    return instance

p = Person()
# output: __new__ called
print(p.developer)
# output: Anjaneyulu Batta
  • In the above code, we have overriden the default behaviour of __new__ method.
  • added an attribute developer

__init__ - initializer

  • __init__ is the object initializer
  • It is used when we want the object to hold the given values in the class attributes
  • Let's look at an example
class Rectange:
  def __init__(self, length, width):
    self.length = length
    self.width = width

rect = Rectange(10, 30)

print(rect.length)
# output: 10
print(rect.width)
# output: 30
  • In the above example, we have initialized the rect object with length and width attributes

__str__ - object representation as string

  • __str__ method is used to represent the object in string notation
  • Let's look at an example
class Point:
  def __init__(self, x, y):
    self.x = x
    self.y = y

p = Point(10, 20)

print(p)
# output: <__main__.Point object at 0x102c953d0>
  • without __str__ method it will print output like <main.Point object at 0x102c953d0>
  • let's add __str__ method and print it
class Point:
  def __init__(self, x, y):
    self.x = x
    self.y = y

  def __str__(self):
    return f'Point({self.x}, {self.y})'

p = Point(10, 20)

print(p)
# output: Point(10, 20)
  • after adding __str__ it will print the output like Point(10, 20)

instance method

  • To use instance method, we need to create an object from class
  • Can just call the method just like function on the object with .
  • Let's look at an exmaple
class Circle:
  def __init__(self, radius):
    self.radius = radius

  def get_area(self):
    return 3.14 * self.radius ** 2

c = Circle(10)
area = c.get_area()
print(area)
# output: 314.0
  • For any instance method self is the first argument.

classmethod

  • To use class method we don't need to create the class object.
  • To define any class method we need @classmethod decorator
  • Like instance method, it passes the first argument as class.
  • Let's see an example
class Date(object):
  def __init__(self, day=0, month=0, year=0):
    self.day = day
    self.month = month
    self.year = year

  def __str__(self):
    return f'{self.day}/{self.month}/{self.year}'

  @classmethod
  def from_string(cls, date_as_string):
    day, month, year = map(int, date_as_string.split('-'))
    obj = cls(day, month, year)
    return obj

d = Date.from_string("25-10-2022")
print(d)
# output: 25/10/2022
  • In the above code, we can see that the method from_string(cls, date_as_string) has the first param as cls which is nothing but Date class.
  • By default python passes the argument cls along with user specified arguments.

staticmethod

  • It's just like normal python function that just defined inside the class
  • Like classmethod it also required to use decorator staticmethod
  • Let's look at an example
class Claci:
  @staticmethod
  def add(x, y):
    return x + y

  @staticmethod
  def mul(x, y):
    return x * y

print(Calci.add(10, 20))
# output: 30
  • From the above code, we can see that we don't need to create an instance and no default argument is passed.

References