Getting Started

Python - IntroductionPython - Hello World ProgramPython - SyntaxPython - Data TypesPython - Variables

Operators

Python - Arithmetic OperatorsPython - Relational OperatorsPython - Logical OperatorsPython - Assignment OperatorsPython - Bitwise OperatorsPython - Membership OperatorsPython - Identity OperatorsPython - Increment and Decrement Operators

Conditions

Python - If Else statement

Loop

Python - While LoopPython - For Loop

Numbers

Python - NumbersPython - Number Conversion

Strings

Python - StringsPython - String OperatorsPython - String FormattingPython - String MethodsPython - String Format Method

List

Python - ListPython - List Methods

Tuple

Python - Tuple

Set

Python - SetPython - Set Methods

Dictionary

Python - DictionaryPython - Dictionary Methods

Functions

Python - FunctionsPython - Functions - Variable length argumentsPython - Lambda Function

Scope of Variables

Python - Scope of Variables

Modules

Python - ModulesPython - Math ModulePython - JSON ModulePython - datetime ModulePython - time Module

I/O

Python - Read input from keyboard

File

Python - File Handling

Exception Handling

Python - Exception Handling

OOP

Python - Classes and ObjectsPython - Class Constructor __init__ methodPython - Class Destructor __del__ methodPython - Built-in Class AttributesPython - InheritancePython - Method OverridingPython - Method Overloading

Package Management

Python - PIP

Python - MySQL

Python - MySQL - Getting StartedPython - MySQL - Insert dataPython - MySQL - Select dataPython - MySQL - Update dataPython - MySQL - Delete data

Python - CSV

Python - Read data from CSV filePython - Write data in CSV file

Python - Classes and Objects

Python

python logo

In this tutorial we will learn about classes and objects in Python.

Python is an object oriented programming (OOP) language. Everything in Python is an object which consists of some methods and properties (attributes).

What is a class?

A class is a blueprint which is used to create objects. Classes consists of properties (attributes) and methods.

We create classes using the class keyword in Python.

Syntax:

class className:
  #
  # some code goes here...
  #

Where, className is the name of the class.

Rules to name a class

Following are the rules to name a class.

  • Class name must use upper-camel-case like MyAwesomeClass.
  • Keep class name short and meaningful.
  • Don't start the class name with a digit.
  • Don't use Python keywords to name the classes.

What is an object?

An object is an instance of a class.

For example, if a class is a blueprint of a house then an object is the actual house constructed using the blueprint.

We create object of a class by writing the name of the class followed by parenthesis.

Syntax:

# class
class MyAwesomeClass:
  #
  # some code goes here...
  #

# object of the class
obj = MyAwesomeClass()

Adding class attributes

We can add variables inside a class which are called attributes (properties) of the class.

In the following Python program we are creating a class having an attribute.

# class
class Awesome:

    # attribute common to all the objects of this class
    foo = 0

# objects of the class
obj1 = Awesome()
obj2 = Awesome()

Setting value of class attributes

We use the following notation to set the value of the class attribute that is common to all the objects of the class.

ClassName.attr = val

Where, ClassName is the name of the class and attr is a class attribute. val is the value that we are assigning to the class attribute.

In the following Python program we are setting the value of the class attribute that is common to all the objects of the class.

# class
class Awesome:

    # attribute common to all the objects of this class
    foo = 0

# value of foo before any object
print("before: foo =", Awesome.foo)

# object of the class
obj1 = Awesome()

# add 1 to foo
Awesome.foo = Awesome.foo + 1

print("after obj1: foo =", Awesome.foo)

# object of the class
obj2 = Awesome()

# add 1 to foo via obj2
obj2.foo = obj2.foo + 1

print("after obj2: foo =", obj2.foo)

We will get the following output.

before: foo = 0
after obj1: foo = 1
after obj2: foo = 2

Adding class methods

We can add methods to classes using the def keyword.

Class methods are very simiar to functions.

In the following Python program we are adding greetings method to the Awesome class.

# class
class Awesome:

    # attribute common to all the objects of this class
    foo = 0

    # method common to all the objects of this class
    def greetings(self):
        print("Hello World")

# object of the class
obj = Awesome()

# calling class method
obj.greetings()

The above code will print Hello World.

Note! The first parameter of every method of the class is self.

The self keyword refers to the current object of the class and is used to access attributes and methods of the class from inside the class.

When calling the method of the class via the object we don't have to pass the self as an argument.

Accessing attributes and methods using self

In the following Python program we are accessing class attribute and method using the self keyword.

# class
class Awesome:

    # attribute common to all the objects of this class
    foo = 0

    # methods common to all the objects of this class
    def greetings(self):
        print("Hello World")

    def output(self):
        # calling greetings method
        self.greetings()

        # printing foo value
        print("foo from Awesome class:", self.foo)

# object of the class
obj = Awesome()

# updating foo value
obj.foo = 10

# calling class method
obj.output()

The above code will print the following output.

Hello World
foo from Awesome class: 10

Explanation:

In the above example we are first creating an object of the Awesome class.

Then, using the obj object we are updating the value of foo.

Then, we are calling the output() method of the Awesome class.

Inside the output() method we are calling the greetings() method using the self keyword. The greetings() method prints the string "Hello World".

Finally, using the self keyword we are printing the value of the foo attribute.