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:",name,", salary:",salary)
# Print the details of the employee
name = input("name: ")
salary = int(input("salary: "))
emp = Employee(name, salary)
emp.displayEmployee()

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.