Unit 5 - Lesson 3 | Codetantra Python

Unit 5 - Lesson 3 | Codetantra Python

Unit 5 - Lesson 3

52.1.1. Constructor - An introduction

(a) A constructor can be viewed as a specific method used by the class to perform tasks such as initialising variables, or any start up task.
(b) In Java language, the constructor has the same name as the class with no return type defined.
(d) A constructor in Python in any class is defined as __init__(self) method.

52.1.2. Writing a class using __init__ method

class Student:

    def __init__(self,name,age):
        self.name = name
        self.age = age
#fill in the missing code..


name = input("s1 name: ")
age = int(input("s1 age: "))
Stud_1 = Student(name,age)

name = input("s2 name: ")
age = int(input("s2 age: "))
Stud_2 = Student(name,age)

print('Stud_1.name:', Stud_1.name)
print('Stud_2.name:', Stud_2.name)

52.1.3. Using the init method in the class

class Student:
#fill in the missing code.. 

    def __init__(self,name,age,email):
        self.name = name
        self.age = age
        self.email = email

    def studentDetails(self):
        print("name:", self.name,", age:", self.age,", email:", self.email)

name = input("name: ")
age = int(input("age: "))
email = input("email: ")
s1 = Student(name, age, email)
s1.studentDetails()

52.1.4. Write a program to print name and salary of an Employee and print total salary of all Employees.

class Employee:
    def __init__(self, name, salary):
        # Initialize name and salary of the employee
        self.name = name
        self.salary = salary

    def displayEmployee(self):
        # Write a function to display employee details
        print("name:",self.name,", salary:",self.salary)
# Print the details of the employee
name = input("name: ")
salary = int(input("salary: "))
emp = Employee(name, salary)
emp.displayEmployee()