0% found this document useful (0 votes)
4 views

Python Constructors

The document explains different types of Python constructors, including default, parameterized, constructors with default values, constructors with validation, and constructors in inheritance. It provides code examples for each type, illustrating how they function and their usage. The document emphasizes the importance of constructors in initializing objects in Python.

Uploaded by

yoeurthsaiyann20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Constructors

The document explains different types of Python constructors, including default, parameterized, constructors with default values, constructors with validation, and constructors in inheritance. It provides code examples for each type, illustrating how they function and their usage. The document emphasizes the importance of constructors in initializing objects in Python.

Uploaded by

yoeurthsaiyann20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Python Constructors

1. Default Constructor (No Parameters)


This constructor does not take any parameters.

class Animal:
def __init__(self):
print("An Animal is created!")

a1 = Animal()

2. Parameterized Constructor
A constructor that takes arguments.

class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
c1 = Car("Toyota", "Corolla")
print(c1.brand, c1.model) # Toyota Corolla

3. Constructor With Default Values


Setting default values for constructor parameters.

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

e1 = Employee()
e2 = Employee("John", 5000)
print(e1.name, e1.salary) # Unknown 3000
print(e2.name, e2.salary) # John 5000

4. Constructor With Validation


Adding validation inside the constructor.
class Student:
def __init__(self, name, age):
if age < 0:
raise ValueError("Age cannot be negative!")
self.name = name
self.age = age

s1 = Student("Alice", 20)

5. Constructor in Inheritance
Using a parent class constructor in a subclass.

class Animal:
def __init__(self, species):
self.species = species

class Dog(Animal):
def __init__(self, name, breed):
super().__init__("Dog")
self.name = name
self.breed = breed
d1 = Dog("Buddy", "Golden Retriever")
print(d1.species, d1.name, d1.breed)

You might also like