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
Accessing Object Properties
You can access properties using dot notation:
object_name.property_name
Example: Access Properties
Modifying Properties
Object properties can be updated after the object is created.
Example: Update a Property Value
Deleting Properties
You can remove a property from an object using the
del keyword.
Example: Delete a Property
Class Properties vs Instance Properties
Python supports two types of properties:
[Image contrasting Class Properties shared among all instances versus Instance Properties unique to each object]| Property Type | Description |
|---|---|
| Instance Properties |
Defined inside
__init__()
and are unique to each object.
|
| Class Properties | Defined directly inside the class body and are shared by all objects. |
Example: Class vs Instance Property
Modifying Class Properties
When a class property is modified using the class name, the change affects all objects created from that class.
Example: Update a Class Property
Adding New Properties to Objects
Python allows you to add new properties to objects dynamically, even after they have been created. This newly added property will only exist for that specific object.
