In this tutorial, we will be discussing methods and constructors in detail. If you are familiar with any other object-oriented programming language, then the concept will be easy for you to grasp. So, let us begin with the Method.
A method is just like a function, with a def keyword and a single parameter in which the name of the object has to be passed. The purpose of the method is to show all the details related to the object in a single go. We choose variables that we want the method to take but do not have to pass all of them as parameters. Instead, we have to set the parameters we want to include in the method during its creation. Using methods make the process simpler and a lot faster.
The self keyword is used in the method to refer to the instance of the current class we are using. The self keyword is passed as a parameter explicitly every time we define a method.
def read_number(self):
print(self.num)
"__init__" is also called as a constructor in object-oriented terminology. Whereas a constructor is defined as:
"Constructor in Python is used to assign values to the variables or data members of a class when an object is created."
Python treats the constructor differently as compared to C++ and Java. The constructor is a method with a def keyword and parameters, but the purpose of a constructor is to assign values to the instance variables of different objects. We can give the values by accessing each of the variables one by one, but in the case of the constructor, we pass all the values directly as parameters. Self keyword is used to assign value to a constructor too.
As there can be only one constructor for a specific class, so the name of the constructor is a constant, i.e., __init__.
We declare a constructor in Python using def keyword,
def __init__(self):
# body of the constructor
Here,
For Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
#Output: John
We have two types of constructors in Python.
Methods and functions are very similar, yet there are some differences:
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}"
harry = Employee("Harry", 255, "Instructor")
# rohan = Employee()
# harry.name = "Harry"
# harry.salary = 455
# harry.role = "Instructor"
#
# rohan.name = "Rohan"
# rohan.salary = 4554
# rohan.role = "Student"
print(harry.salary)
No downloadable resources for this video. If you think you need anything, please post it in the QnA!
Any Course related announcements will be posted here
Be the first person to comment!