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:
45000
Accessing Object Properties
You can access properties using dot notation:
object_name.property_name
Example: Access Properties
Output:
30000
Modifying Properties
Object properties can be updated after the object is created.
Example: Update a Property Value
Output:
95
Deleting Properties
You can remove a property from an object using the del keyword.
Example: Delete a Property
Output:
Error: 'Player' object has no attribute 'level'
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:
Cat
Mammal
Mammal
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
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@example.com
1200
