Class Properties in Python

Class Properties in Python

Kishore V


Class Properties in Python

Properties are variables that store data inside a class or its objects.

Each object created from a class can have its own set of properties.

Defining Properties in a Class

Most properties are defined inside the __init__() method.

These are called instance properties because they belong to individual objects.

Example: Create a Class with Properties

Output:

101
45000
Try it Yourself

Accessing Object Properties

You can access properties using dot notation:

object_name.property_name

Example: Access Properties

Output:

Samsung
30000
Try it Yourself

Modifying Properties

Object properties can be updated after the object is created.

Example: Update a Property Value

Output:

80
95
Try it Yourself

Deleting Properties

You can remove a property from an object using the del keyword.

Example: Delete a Property

Output:

Neo
Error: 'Player' object has no attribute 'level'
Try it Yourself

Class Properties vs Instance Properties

Python supports two types of properties:

Instance Properties

  • Defined inside __init__()
  • Unique to each object

Class Properties

  • Defined directly inside the class
  • Shared by all objects

Example: Class vs Instance Property

Output:

Dog
Cat
Mammal
Mammal
Try it Yourself

Modifying Class Properties

When a class property is modified, the change affects all objects created from that class.

Example: Update a Class Property

Output:

USA
USA
Try it Yourself

Adding New Properties to Objects

Python allows you to add new properties to objects dynamically, even after creation.

Example: Add Properties at Runtime

Output:

Rahul
rahul@example.com
1200
Try it Yourself

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