In this tutorial we are going to learn :
- Classes in Python
- Creating A Class
- Constructors
- Private Members
Â
Â
Â
Classes in Python
Python is an object-oriented programming language. Almost everything in Python is an object.
Important concepts :
- Class : helps us to create an object and it is simply a blueprint of an object.
- Object : an instance of a class.
- Method : A function which is created in the class.
- Attributes : A variable bound to an instance of a class.
Let’s give an example Class and Object
Class : Animal
Object : Cat, Dog, Bird.
Â
Â
Creating A Class
We use the class keyword to create a class.
Note :
Class name rule : First letter of each internal word should be upper case.Â
Example:
class MyClass: # creating a class
def person(self):
print("Hello")
my_class = MyClass() # creating an object called my_class
my_class.person()

Â
Â
Â
Â
Constructors
The example programs above are classes and objects in their simplest form. To understand the meaning of classes we have to understand the constructors ( __init__ function ) .
- All classes have __init__ function and it is always executed when the class is being
initiated.
Example :
As you can see when we create a constructor and create variables we can access his variables from outside.
- the self parameter is a reference to the current instance of the object. So we can access the variables.

Â
Â
Example :Â
class MyClass:
def __init__(self, first, second):
self.first = first
self.second = second
my_class = MyClass(1,2)
print(my_class.first)

Â
Â
Example :Â
- The self parameter is a reference to the current instance of the class and we use to access variables that belong to the class.
class MyClass:
def __init__(self, first, second):
self.first = first
self.second = second
def number(self):
print(f"First Number {self.first}, Second Number {self.second}")
my_class = MyClass(1, 2)
my_class.number()

Private Members
To make our variables private, we use double underscores ( __ ) .
Example :
- As you can see we can’t access our private name variable and our program raise an error.

