xxxxxxxxxx
# If you are familiar with C++ or Java think of the __init__ method as a constructor.
# It is the method that is being called when the class is initiated.In the following
# example we will see how we can call the __init__ method
my_variable = MyClass()
xxxxxxxxxx
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36) // Object definition
print(p1.name)
print(p1.age)
xxxxxxxxxx
class MyClass(object):
i = 123
def __init__(self):
self.i = 345
a = MyClass()
print(a.i)
print(MyClass.i)
# Output:
# 345
# 123
xxxxxxxxxx
class Square(object):
def __init__(self, number = 2):
self._number = number
def square(self):
return self._number**2
s = Square()
print('Number: % i' % s._number)
print('Square: % i' % s.square())
In Python, __init__ is a function or function Object() { [native code] }. When a new object/instance of a class is created, this function is automatically called to reserve memory. The __init__ method is available in all classes.
Here's an instance of how to put it to good use.
xxxxxxxxxx
# Python program to explain __init__
class Student:
def __init__(self, st_name, st_class, st_marks):
self.st_name = st_name
self.st_class = st_class
self.st_marks = 67
S1 = Student("Itika", 10, 67)
print(S1.st_name)
print(S1.st_class)