Signup/Sign In

Python Class

In this tutorial, we will learn how to define a class in Python.

As discussed in last tutorial, classes are collection of variables, and functions, that are bound together.


Syntax for defining a class

Defining a class is simple, all you have to do is use the keyword class followed by the name that you want to give your class, and then a colon symbol :. It is standard approach to start the name of class with a capital letter and then follow the camel case style.

The class definition is included, startring from the next line and it should be indented, as shown in the code below. Also, a class can have variables and member functions in it.

class MyClass:
    # member variables
	variable1 = something
	variable2 = something
	
	# member functions
	def function1(self, parameter1, ...):
		self.variable1 = something else
		# defining a new variable 
		self.variable3 = something
		function1 statements...
		
	def function2(self, parameter1, ...):
		self.variable2 = something else
		function2 statements...

Let's try to understand the code above, although it is self explanatory. As already explained, we have used the keyword class, to inform the compiler that from here a new class definition starts, followed by the name of the class i.e., MyClass.

In Line 2 we have added a comment and in line 3 and 4, we declared two variables variable1 and variable2 and have also initialised them with some values.

This is just a sample to explain how we define a class, we will see an example for class, after this section.

Further below there are two functions defined. Again, we have mentioned sample functions just to explain the syntax.

As you can see in the code, it's pretty much the usual function definition like we do without a class, using the def keyword, except for a new parameter named self. This is what makes class's function different from the usual function.

It's a mandatory parameter for every function defined in a class. self represents the current active object of the class, using which the function of the class is called. Don't worry if you are not able to understand it, we will explain this again when we will learn about objects.

This was how we define a class in python, now let's understand how to create an instance/object of a class


Creating object for a class

Class is mere a blueprint or a template. No storage is assigned when we define a class. Objects are instances of class, which holds the data variables declared in the class and the member functions work on these class objects.

To create an object, all we have to do is:

myObject = MyClass()

where, MyClass is the name of the class and myObject is the object variable

As you can see, we simply specified the object's name and we called a function which had the same name as of the class to which it belongs.

Do you remember how we were able to initialize a list by writing myList = list(). Similar is the case here, we have created a user-defined data type(a class) called MyClass, and in order to inform python that myObject variable will be of that datatype, we make a call to this function.


Time for an Example

Till now, it was just the theory, to help you understand how classes are defined and how objects are created in python. Next, we will see how the objects are used to call the member functions and variables (which are defined in the class).

Let's write a small python program in which we will define a class with one variables and two methods, and then we will create an object of that class and will try to access the variable and member functions.

class Apollo:
    # define a variable
    destination = "moon";
    
    # definig the member functions
    def fly(self):
        print ("Spaceship flying...");
    
    def get_destination(self):
        print ("Destination is: " + self.destination)

We have defined a class with name Apollo. As you can see that in the function get_destination we have written self.destination this will give the value stored in the variable destination for the object for which the function get_destination will be called.

Confused? Don't worry, you will understand it, let's quickly create two objects for this class. So to create objects, we know what to do,

class Apollo:
    # define a variable
    destination = "moon"
    
    # defining the member functions
    def fly(self):
        print ("Spaceship flying...");
    
    def get_destination(self):
        print ("Destination is: " + self.destination);
        
# 1st object
objFirst = Apollo()
# 2nd object
objSecond = Apollo()

Now we have defined two objects for our class. As of now, both our objects have a variable destination in them, which is assigned the value "moon".

To access any member variable or a member function using the object, we use a . (dot), as shown below.

class Apollo:
    # define a variable
    destination = "moon"
    
    # defining the member functions
    def fly(self):
        print ("Spaceship flying...");
    
    def get_destination(self):
        print ("Destination is: " + self.destination);
        
# 1st object
objFirst = Apollo();
# 2nd object
objSecond = Apollo();

# lets change the destination for objFirst to mars
objFirst.destination = "mars";

In the code above, we have now updated the value for the variable destination to "mars" for the object objFirst

Now let's call the member functions.

class Apollo:
    # define a variable
    destination = "moon"
    
    # defining the member functions
    def fly(self):
        print ("Spaceship flying...");
    
    def get_destination(self):
        print ("Destination is: " + self.destination);
        
# 1st object
objFirst = Apollo();
# 2nd object
objSecond = Apollo();

# lets change the destination for objFirst to mars
objFirst.destination = "mars";

# objFirst calling fly function
objFirst.fly();
# objFirst calling get_destination function
objFirst.get_destination();

# objSecond calling fly function
objSecond.fly();
# objSecond calling get_destination function
objSecond.get_destination();

Spaceship flying... Destination is: mars Spaceship flying... Destination is: moon

Few points to note:

  1. We add the self parameter when we define a member function, but do not specify it while calling the function.
  2. When we called get_destination function for objFirst it gave output as Destination is: mars, because we updated the value for the variable destination for the object objFirst
  3. To access a member function or a member variable using an object, we use a dot . symbol.
  4. And to create an object of any class, we have to call the function with same name as of the class.