Python Programming Primer

Classes and Objects


Python is an object-oriented programming language (everything in Python is an object) and it supports creating classes and objects.

Object-oriented programming is a programming paradigm that centers around objects that can contain data and functionality. Objects are created out of classes that define both the properties (data) and methods (functionality) that the objects have.

The following outlines how to define a class, create an object out of the class, to print the property of the object.

Run the program to see the output

Loading Exercise...

The following example extends the previous example by adding a method to the class. The method is used to print the object’s properties.

Run the program to see the output

Remember the chatbot!

If you’re unsure about how the above code works, now is an excellent time to ask the LLM chatbot to explain it. Like earlier, you can open it by clicking the bot-icon on the lower right corner of this page.

The methods — functions within class that are used to interact with the object — are defined inside the class. The __init__ method is a constructor that is called when the object is created. The self parameter is used to refer to the object itself. The following outlines how to define a class with two methods — one that prints the object another that modifies the name property of the object.

Run the program to see the output

Although the above example uses a method to modify the object, the object’s attributes can also be modified directly, as shown below.

Run the program to see the output

Private instance variables

Python does not feature private instance variables per se, i.e. the variables can always be accessed from outside. One practice for denoting variables as private is to prefix the variable name with an underscore (self._name). This is a convention that is used by many Python programmers.

Although Python is an object-oriented programming language, like most contemporary programming languages, Python is a multi-paradigm language that allows following multiple programming paradigms.


Loading Exercise...