Skip to main content

Class Properties

A property is a variable that lives in a class. It holds data for every object built from it.

Example

A class that has properties:

Prompt
Create a Person class with name and age properties using init, create an object and print the properties.
Output: complete Python program

Access Properties

Dot notation is how you read a property of an object:

Example

Read an object's properties:

Prompt
Create a Car class with brand and model, create an object and access properties using dot notation.
Output: complete Python program

Modify Properties

You can change a property's value on an object:

Example

Update the age property:

Prompt
Create a Person object, print age, change age to 26, and print again.
Output: complete Python program

Delete Properties

The del keyword removes a property from an object:

Example

Remove the age property:

Prompt
Create a Person object with name and age, delete the age property using del, then print name.
Output: complete Python program

Class Properties vs Object Properties

A property defined inside __init__() belongs to each object (an instance property).

One defined outside any method belongs to the class itself (a class property), and all objects share it:

Example

An instance property next to a class property:

Prompt
Show the difference between a class property (species) and instance properties (name) in a Person class.
Output: complete Python program

Modifying Class Properties

Changing a class property changes it for every object:

Example

Assign a new value to a class property:

Prompt
Demonstrate how modifying a class property affects all objects by setting Person.lastname.
Output: complete Python program

Add New Properties

An object that already exists can still receive new properties:

Note: A property added this way exists only on that object, not on the others.

Example

Give an object an extra property:

Prompt
Create a Person object and add new properties (age, city) after creation, then print all.
Output: complete Python program