what does __init__ do in python code example
Example 1: __init__ python
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)
Example 2: self and init in python
class Computer:
def __init__(self):
self.name= ("Pankaj")
self.age= 28
c1=Computer()
c2=Computer()
c1.name= "Garg"
print(c1.name)
print(c2.name)
Example 3: what is init class python
The __init__ function serves two main purposes.
The first is its used as a tool to pass
arguments inside of it but the difference is you can spread those
arguments to other functions located in the same class.
To do this you would place the word (self.) keyword in another function
followed by the arguments name. This allows the argument to be spread
down to that function.
The second purpose is it allows you to pass arguments to a
class when calling the class. Without this function inside the class
when you call the class no arguments would be able to go inside getting
nothing in return.
Example 4: what is __init__ in python
my_variable = MyClass()
Example 5: init function in python
class Rectangle:
def __init__(self, length, breadth, unit_cost=0):
self.length = length
self.breadth = breadth
self.unit_cost = unit_cost
def get_area(self):
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s sq units" % (r.get_area()))
Example 6: def __init__
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount