
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
What is difference between self and __init__ methods in python Class?
self
The word 'self' is used to represent the instance of a class. By using the "self" keyword we access the attributes and methods of the class in python.
__init__ method
"__init__" is a reseved method in python classes. It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.
Example
Find out the cost of a rectangular field with breadth(b=120), length(l=160). It costs x (2000) rupees per 1 square unit
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 # breadth = 120 units, length = 160 units, 1 sq unit cost = Rs 2000 r = Rectangle(160, 120, 2000) print("Area of Rectangle: %s sq units" % (r.get_area()))
Output
This gives the output
Area of Rectangle: 19200 sq units Cost of rectangular field: Rs.38400000
- Related Articles
- Difference between title() and wm_title() methods in Tkinter class
- self in Python class
- What is the difference between re.match(), re.search() and re.findall() methods in Python?
- What is the difference between re.findall() and re.finditer() methods available in Python?
- What is the difference between re.search() and re.findall() methods in Python regular expressions?
- What is the difference between non-static methods and abstract methods in Java?
- What is the difference between functions and methods in JavaScript?
- What is the difference between scipy.cluster.vq.kmeans() and scipy.cluster.vq.kmeans2() methods?
- What are the differences between class methods and class members in C#?
- What is Regex class and its class methods in C#?
- What is the difference between Component class and Container class in Java?
- What is the difference between switchClass() and toggleClass() methods in jQuery?
- What is the difference between $.closest() and $.parents() methods in jQuery?
- What is the difference between jQuery.offsetParent( ) and jQuery.parent() methods in jQuery?
- What is the difference between jQuery.html( ) and jQuery.append( ) methods in jQuery?

Advertisements