Python Class and Its Components

Python Class

What is a Python Class?

- A Python class is like an outline for creating a new object.

- An object is anything that you wish, you can change while working on the code.

- Python has a reserved keyword known as “class” which you can use to define a class.

- Every object can use class variablesinstance variables, and functions.


How to Create a Class in Python?

There are the following components that you need to know while working with classes in Python:

1. The “class” keyword

- We can create the class with the class keyword.

- In the below code, the class name is chirag.


2. The class attributes

- Variable of the class that is shared in all its objects.

- In the below code, age is the class variable that is shared with the h1 object.

- To return the value of ageprint(h1.age)



3. The “__init__” method

- The “__init__()” is a constructor/method which is used for initializing the instance variables during object creation.

- It is commonly known as a Constructor in object-oriented programming.

- An init is fixed with a double underscore (__).

- We declare a constructor using the def keyword.

- Syntax: def __init__(self):


4. The “self” keyword

- The self-keyword is used to 
access instance variables that belong to the class.


5. The instance attributes

- These attributes are defined inside the "__init__constructor/method using the self-parameter.

In the below code, self.habit = habit is the instance attribute.


6. Object of a class

- The object of a class is used to pass the values of the class and instance variables.

- In the below code, h1 is the object of the chirag class.

Comments