python: understand 'self' and '__init__'

reference:

  1. https://micropyramid.com/blog/understand-self-and-__init__-method-in-python-class/
  2. https://stackoverflow.com/questions/8609153/why-do-we-use-init-in-python-classes

 

Before understanding the "self" and "__init__" methods in python class, it's very helpful if we have the idea of what is a class and object.

  • Class : Class is a set or category of things having some property or attribute in common and differentiated from others by kind, type, or quality. In technical terms we can say that class is a blue print for individual objects with exact behaviour.
  • Object : object is one of instances of the class. which can perform the functionalities which are defined in the class.
  • self : 'self' represents the instance of the class. By using the "self" keyword we can access the attributes and methods of the class in python.
  • __init__ : "__init__" is a reseved method in python classes. It is known as a constructor in object oriented concepts. This method called when an object is created from the class and it allow the class to initialize the attributes of a class.

How can we use  "__init__ " ?

Let's consider that you are creating a NFS game. for that we should have a car. Car can have attributes like "color", "company", "speed_limit" etc. and methods like "change_gear", "start", "accelarate", "move" etc.

class Car(object):
	"""
		blueprint for car
	"""

	def __init__(self, model, color, company, speed_limit):
		self.color = color
		self.company = company
		self.speed_limit = speed_limit
		self.model = model

	def start(self):
		print("started")

	def stop(self):
		print("stopped")

	def accelarate(self):
		print("accelarating...")
		"accelarator functionality here"

	def change_gear(self, gear_type):
		print("gear changed")
		" gear related functionality here"
Lets try to create different types of cars
maruthi_suzuki = Car("ertiga", "black", "suzuki", 60)
audi = Car("A6", "red", "audi", 80)
We have created two different types of car objects with the same class. while creating the car object we passed arguments  "ertiga", "black", "suzuki", 60  these arguments will pass to "__init__" method  to initialize the object. 
Here, the magic keyword "self"  represents the instance of the class. It binds the attributes with the given arguments.

Usage of "self" in class to access the methods and attributes

Case: 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_perimeter(self):
       return 2 * (self.length + self.breadth)
   
   def get_area(self):
       return self.length * self.breadth
   
   def calculate_cost(self):
       area = self.get_area()
       return area * self.unit_cost
# breadth = 120 cm, length = 160 cm, 1 cm^2 = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s cm^2" % (r.get_area()))
print("Cost of rectangular field: Rs. %s " %(r.calculate_cost()))

As we already discussed  "self" represents the same object or instance of the class. If you see, inside the method "get_area"  we have used "self.length" to get the value of the attribute "length".  attribute "length" is bind to the object(instance of the class) at the time of object creation. "self" represents the object inside the class. "self" works just like "r" in the statement  "r = Rectangle(160, 120, 2000)".  If you see the method structure "def get_area(self): "  we have used "self" as a parameter in the method because whenever we call the method, the object (instance of class) automatically passes as a first argument along with other argumets of the method. If no other arguments are provided only "self" is passed to the method. That's the reason we use "self" to call the method inside the class("self.get_area()").  we use object( instance of class) to call the method outside of the class definition("r.get_area()"). "r" is the instance of the class, when we call method "r.get_area()"  the instance "r" is passed as as first argument in the place of self.
 

r = Rectangle(160, 120, 2000)


Note: "r" is the representation of the object outside of the class and "self"  is the representation of the object inside  the class.

for more details please visit python documentation

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值