In object-oriented programming, the term "constructor" refers to a special type of method that is automatically executed when an object is created from a class.
The purpose of a constructor is to initialize the object's attributes, allowing the object to be fully functional and ready to use.
However, there are times when we may want to create an object in a different way, or with different initial values, than what is provided by the default constructor.
This is where class methods can be used as alternative constructors.
A class method belongs to the class rather than to an instance of the class.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
,
)?from_string
" to do this: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)) #creating an instance of Person class
#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 that needs a different set of default values than what is provided by the default constructor.
"Rectangle"
that has two attributes: "width"
and "height"
. "height"
& "width"
parameters.
"square"
object that's height & width are same, we can use a class-Method "square_inp"
to return the size twice as "height"
& "width"
parameters.class Rectangle:
def __init__(self, width, height):
self.width = width #parameters
self.height = height
def square(self):
return(f'The square is {self.height * self.width} cm^2')
@classmethod
def square_inp(cls, size):
return cls(size, size) # returning 2 size values
rectangle = Rectangle.square_inp(10)
print(rectangle.square())
#Output:
The square is 100 cm^2