Skip to main content

Python Classes/Objects

Object-oriented programming is at the heart of Python, where nearly everything is an object with properties and methods of its own.

To make objects you need a class, which acts as a constructor or "blueprint" for them.


Create a Class

The class keyword starts a new class:

Example

A class called MyClass with one property, x:

Prompt
Create a class named MyClass with a property named x set to 5.
Output: complete Python program

Create Object

With MyClass defined, we can build objects from it:

Example

Make an object called p1, then print its x value:

Prompt
Create an object named p1 from the MyClass class and print the value of x.
Output: complete Python program

Delete Objects

The del keyword removes an object you no longer want:

Example

Remove the p1 object:

Prompt
Create an object from MyClass, print its x property, then delete the object using del.
Output: complete Python program

Multiple Objects

A single class can produce as many objects as you like:

Note: Every object is a separate instance, so giving one object its own value for a property does not affect the others.

Example

Build three objects from MyClass:

Prompt
Create three objects from the MyClass class and print each object's x property.
Output: complete Python program

The pass Statement

Python does not allow an empty class definition. If you need one with no content for now, write the pass statement inside it and the error goes away.

Example

Prompt
Create a class named Person with no content using the pass statement.
Output: complete Python program