Python Classes and Objects

Python Classes and Objects

Kishore V


Python Classes and Objects

Python follows the object-oriented programming (OOP) paradigm.

In Python, almost everything is an object, and every object contains:

  • Attributes (data)
  • Methods (functions)

A class acts as a template or blueprint used to create objects.

Creating a Class

To define a class in Python, use the class keyword followed by the class name.

Example: Define a Simple Class

Output:

<class '__main__.Book'>
Try it Yourself

Here:

  • Book is the class
  • pages is a class attribute

Creating Objects from a Class

Once a class is defined, you can create objects (instances) from it.

Example: Create an Object and Access a Property

Output:

250
Try it Yourself

Creating Multiple Objects

You can create any number of objects from the same class.

Each object is a separate instance but follows the same class structure.

Example: Multiple Objects from One Class

Output:

250
250
250
Try it Yourself

Object Independence

Although objects are created from the same class, they are independent of each other.

Changes made to one object do not automatically affect the others (unless using shared class variables intentionally).

Deleting Objects

Python allows you to delete objects using the del keyword.

After deletion, the object can no longer be accessed.

Example: Delete an Object

Output:

Error: name 'device' is not defined
Try it Yourself

Attempting to use device after deletion will result in an error.

The pass Statement in Classes

A class definition cannot be empty.

If you need a class without content (for planning or future use), use the pass statement.

Example: Empty Class Definition

Output:

<__main__.Employee object at 0x7f9a2b3c4d50>
Try it Yourself

Our website uses cookies to enhance your experience. Learn More
Accept !