What Is The Difference Between Function and Method? Explain The Working of The Init Method With Suitable Code
What Is The Difference Between Function and Method? Explain The Working of The Init Method With Suitable Code
Explain
the working of the init method with suitable code.
A] METHOD
Python Method
1. Method is called by its name, but it is associated to an
object (dependent).
2. A method is implicitly passed the object on which it is invoked.
3. It may or may not return any data.
4. A method can operate on the data (instance variables) that is
contained by the corresponding class
Functions
1. Function is block of code that is also called by its name.
(independent)
2. The function can have different parameters or may not have any at
all. If any data (parameters) are passed, they are passed
explicitly.
3. It may or may not return any data.
4. Function does not deal with Class and its instance concept.
OUTPUT
-2
9
INIT METHOD
The __init__ method is similar to constructors in C++ and Java.
Constructors are used to initialize the object’s state. The task of constructors
is to initialize(assign values) to the data members of the class when an
object of class is created. Like methods, a constructor also contains
collection of statements(i.e. instructions) that are executed at time of Object
creation. It is run as soon as an object of a class is instantiated. The method
is useful to do any initialization you want to do with your object.
Example:
# A Sample class with init method
class Person:
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Nikhil')
p.say_hi()
OUTPUT
Hello, my name is Nikhil
EXAMPLE 1