Day #70 - Class Methods as Alternative Constructors in Python

Day #70 - Class Methods as Alternative Constructors in Python

ยท

3 min read

Introduction

Welcome to my 70th blog post on the Python journey. On day 70, I learned about how a class method can be used as an alternative constructor to create an object in a different way altogether, or with different initial values than the default constructor. Let's dive into more details and understand this concept.

So let's get started......

Class Methods as Alternative Constructors

  • The term "constructor" in OOPs (object-oriented programming), refers to a special type of method that is automatically executed when an object of a class is created.

  • Constructor is used to initialize the object's attributes, allowing the object to be fully functional and ready to use.

  • However, there will be times wherein we may want to create an object in a different way altogether, or with different initial values, then, in that case, we make use of class methods as alternative constructors.

  • A class method belongs to the class rather than to an instance of the class. One common use case for class methods as alternative constructors

Example - Let's create a class 'Person' with initial data name and age

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

But what if we want to create a Person object from a string that contains the person's name and age, separated by a comma? You can define a class method named "from_string" as below:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_string(cls, string):
        name, age = string.split(',')
        return cls(name, int(age))

Now you can create a Person object from a string like this:

person = Person.from_string("John Doe, 30")

Another common use case for class methods as alternative constructors is when you want to create an object with a different set of default values than what is provided by the default constructor. For example, consider a class named "Rectangle" that has two attributes: "width" and "height". The default constructor for the class might look like this:

class Rectangle:
  def __init__(self, width, height):
    self.width = width
    self.height = height

  @classmethod
  def square(cls, size):
    return cls(size, size)

Now you can create a square rectangle like this:

rectangle = Rectangle.square(10)

Some More Examples -

class Employee:
  def __init__(self, name, salary):
    self.name = name 
    self.salary = salary

  @classmethod
  def fromStr(cls, string):
    return cls(string.split("-")[0], int(string.split("-")[1]))

e1 = Employee("Harry", 12000)
print(e1.name)
print(e1.salary)

string = "John-12000"
e2 = Employee.fromStr(string)
print(e2.name)
print(e2.salary)

Resources Used

You can watch the video of Day#70 by clicking on the below link ๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡

Conclusion

Thanks, guys for going through this blog post. On day 70, I learned about using class methods as alternative constructors in Python. I also wrote 2 programs as an example that created alternative constructors to fetch the values of person's name and age using the split method.

Thank you if you read this post and have found this post useful. I hope you have joined me and are enjoying my magical journey of Python coding. This is it for Day #70

See you in the next one.....


About Me

Hey Guys, I am Chintan Jain from CodeWithJain. I am a trader and content creator. I am also passionate about tech and hence wanted to explore the field of tech. I always wanted to learn to code so I watched many tutorials but procrastinated practicing coding. To get into the habit of coding consistently I am starting to BLOG with HASHNODE on daily basis.

I will document my coding journey from scratch and share my daily learnings in a blog post on HASHNODE. I hope you all will enjoy my content and my coding journey.

So what are you waiting for, smash the FOLLOW and LIKE buttons and follow along my coding journey, a step to create more beautiful digital products and empower people.


ย