Course Content

Class Methods As Alternative Constructors | Python Tutorials For Absolute Beginners In Hindi #57

Before moving forward to our topic, I would like to share with you the link to all the exercises we have done so far. If you are following this course since the beginning then they are a great way for you to test your skills.

In this tutorial, we will learn how we can convert a class method into an alternating constructor. This tutorial is not about "what," as we have seen in previous tutorials, where we learn about new concepts or functionality. But this one is about" how." We will focus more on implementation as we are already familiar with all the concepts we are going to use. In this tutorial, we are going to learn some new skills or techniques other than a new concept.

We learned about constructor and its functionality in tutorial #55, where we had to set all the values as parameters to a constructor. Now we will learn how to use a method as a constructor. It has its own advantages. By using a method as a constructor, we would be able to pass the values to it using a string.

Note that we are talking about a class method, not a static method.

The parameters that we have to pass to our constructor would be the class i.e., cls and the string containing the parameters. Moving on towards the working, we have to use a function "split()," that will divide the string into parts. And the parts as results will be stored in a list. We can now pass the parameters to the constructor using the index numbers of the list or by the concept of *args (discussed in tutorial#43 ).

split():

Let us have a brief overview of the split() function. What split() does is, it takes a separator as a parameter. If we do not provide any, then the default separator is any whitespace it encounters. Else we can provide any separator to it such as full stop, hash, dash, colon, etc. After separating the string into parts, the split() function, stores it into a list in a sequence. For example:

text = "Python tutorial for absolute beginners."
 t = text.split()
 print(t)

 Here, we are not providing it any separator as a parameter, so it will automatically divide, taking whitespace as a separator. 

The output will be a list, such as:

['Python', 'tutorial', 'for', 'absolute', 'beginners.']

Example of Class methods - alternative constructor:

class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

@classmethod 
    def from_dash(cls,string):
          return cls(*string.split("-"))

date1=Date.from_dash("2008-12-5")
print(date1.year)
#Output: 2008

If we want multiple and independent "constructors", we can use class methods. They are usually called factory methods. It does not invoke the default constructor __init__.In the above example, we split the string based on the "-" operator. We first create a class method as a constructor that takes the string and split it based on the specified operator. For this purpose, we use a split() function, which takes the separator as a parameter. This alternative constructor approach is useful when we have to deal with files containing string data separated by a separator.

Code as described/written in the video


class Employee:
    no_of_leaves = 8

    def __init__(self, aname, asalary, arole):
        self.name = aname
        self.salary = asalary
        self.role = arole

    def printdetails(self):
        return f"The Name is {self.name}. Salary is {self.salary} and role is {self.role}"

    @classmethod
    def change_leaves(cls, newleaves):
        cls.no_of_leaves = newleaves

    @classmethod
    def from_dash(cls, string):
        # params = string.split("-")
        # print(params)
        # return cls(params[0], params[1], params[2])
        return cls(*string.split("-"))


harry = Employee("Harry", 255, "Instructor")
rohan = Employee("Rohan", 455, "Student")
karan = Employee.from_dash("Karan-480-Student")

print(karan.no_of_leaves)
# rohan.change_leaves(34)
#
# print(harry.no_of_leaves)

Be the first person to comment!

Comments(0)

Resources

No downloadable resources for this video. If you think you need anything, please post it in the QnA!

Course Announcements

Any Course related announcements will be posted here