logo codesdope

Class in Python


You have stepped into the second part of Python - The object-oriented programming (OOP).

Wait for a while; You came up to here. Have you celebrated this? If not, then go and take a break, because you have put a milestone in your life. Believe me!

Now after your break, let's talk about classes. To understand this, take an example.

You are a student
You have a roll number

You friend is also a student
He also has a roll number and a name.

In the programming world, it's like student is a class having attributes of name and roll number and you and your friends are objects of the student class. This means that both of you will have a name and a roll number.

classes and objects in python

Another example you can think of is that shape is a class and rectangle, square and circle are its object.
Let's start with the simplest thing that we can do with class.

  • Python 2
  • Python 3
class Square():
	pass
x = Square()
x.side = 14
print x.side
class Square():
	pass
x = Square()
x.side = 14
print(x.side)
Output
14

class Square():class is a keyword which is used to define class. Square is the name of the class.
In short, it means that Square is a class.

x = Square() → x is an object of the Square class. It means that x is a Square. There could be more objects and all would be Square.

x.side = 14 → x.side means that we are giving an attribute 'side' to the object of the Square class and setting its value as 14.

Methods inside class


Methods are functions defined in a class. Let’s understand this clearly with the following example.

  • Python 2
  • Python 3
class Square():
	def perimeter(self,side):
		return side*4
a = Square()
print a.perimeter(14)
class Square():
	def perimeter(self,side):
		return side*4
a = Square()
print(a.perimeter(14))
Output
56

Inside the Square class, perimeter is a method (or function) that will return the perimeter if side is passed.

self → 'self' is a keyword in Python. It is a self-referencing pointer. It is necessary to pass 'self' as a parameter if the method is inside a class because when an object calls a method, Python automatically passes an instance of it. So, if we do not write self, we will get an error. Try and see the error.

a = Square() → creates an object 'a' of 'Square' class.

a.perimeter(14) → Here, we have passed 14. It seems that we are only passing 14 but Python automatically passes an instance of the class also. So, two parameters are being passed to match with 'self' and 'side'. Now, in the definition of perimeter, side becomes equal to 14 (def perimeter(self, side)) and 4*side is returned.

Let's get 'self' more clear


'self' is a self-referencing pointer. Suppose, you have made a class named 'Dog'

class Dog():
  def set_name(self):
    self.name = "Doggy"

Before going through this code, suppose you made an object of the Dog class. Now, while doing some operation on Dog class, the Dog class should know to which object of Dog you are dealing with ( because there can be many objects of a class ). 'self' refers to the current object or the object which you are dealing with that time. So, self.name = "Doggy" will make the variable 'name' of that particular object to "Doggy" with which you are dealing at that time.

a = Dog()
  a.set_name()

Here, you have called the method 'set_name' on object 'a'. So, in the definition of the method, 'self.name' will refer to the variable 'name' of object 'a'.

Now, let's discuss about 'def set_name(self):'. Here, we have passed 'self' because while calling a class method, Python automatically passes an instance to the method. So, even if it appears that in 'a.set_name()', we have not passed anything but you can think that Python automatically passed the object 'a'.

So, use of 'self' are:

  • It is passed automatically as the first parameter when you call a method on an instance.
  • It is used if we want to access an instance variable from the instance method, from inside that method.

  • Python 2
  • Python 3
class Student():
	def __init__(self,name):
		self.name = name
a = Student("Sam")
print a.name
class Student():
	def __init__(self,name):
		self.name = name
a = Student("Sam")
print(a.name)
Output
Sam

A student must have a name. So, it would be better if we give the name of the student while making its object. This is what __init__ does.

__init__(self,name) means that we must pass a parameter while making an object of the 'Student' class (or we must pass a value for the name while making an object of the 'Student' class).

self.name = name → 'name' in 'self.name' is an attribute. It implies that the Student class will have some attribute 'name' whereas 'name' on the right side of '=' is the parameter that we will pass (__init__(self,name)).

Remember we had written square.side = 14. self.name = name is also similar. There 'square' was representing a class. Here, 'self' is also representing a class i.e., itself.

a = Student("Sam") → We are making an object 'a' of the Student class and passing a string "Sam" while creating it. This string "Sam" will be passed to def __init__(self,name): and name will take the value "Sam".

In self.name = name, name on the right side is the variable in the method __init__ and name in self.name is an attribute of the Student class (since every student will have a name, so we are assigning a variable name to store those names).

You are now ready with the idea of class, objects and methods. Let's look at an example and get the concept clearer.

  • Python 2
  • Python 3
class Rectangle():
	def __init__(self,l,b):
		self.length = l
		self.breadth = b
	def getArea(self):
		return self.length*self.breadth
	def getPerimeter(self):
		return 2*(self.length+self.breadth)
a = Rectangle(2,4)
print a.getArea()
print a.getPerimeter()
class Rectangle():
	def __init__(self,l,b):
		self.length = l
		self.breadth = b
	def getArea(self):
		return self.length*self.breadth
	def getPerimeter(self):
		return 2*(self.length+self.breadth)
a = Rectangle(2,4)
print(a.getArea())
print(a.getPerimeter())
Output
8
12

Most of the codes must be clear to you.
self.length = l → 'length' is some attribute of the Rectangle class. l is the first parameter that we will pass. (We have to pass two parameters while making an object of the Rectangle class. Our first parameter will become 'l' and the second will become 'b').

return self.length*self.breadth → 'length' and 'breadth' will be defined only to the objects created and not globally, so to access them we have to use 'self'. This will refer to the length and breadth of the object with which we are dealing at that time. So, self.length ('a' is calling) will refer to the length of a i.e. 2.

We have not given you many examples in this chapter. So, go to the practice section and solve questions, ask doubts. That will make a strong foundation of class and object.

Knowing is not enough, we must apply. Willing is not enough, We must do.
- Bruce Lee


Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.