Skip to content

Chapter 6 of 7

Object-Oriented Programming

Python supports object-oriented programming through classes. You define a class with the class keyword, like class MyClass:, followed by indented methods. Instances are created by calling the class as if it were a function: obj = MyClass(). The special __init__ method, defined as def __init__(self, args):, serves as the constructor and is automatically called when an instance is created. The first parameter, conventionally named self, refers to the instance being created.

Classes can have both instance variables and class variables. Instance variables are unique to each object and typically set via self.var, while class variables are shared across all instances of the class and accessed through MyClass.var. Methods are functions defined inside a class that take self as their first parameter, allowing them to access and modify the instance's attributes. They are called on instances using dot notation, as in obj.method().

Inheritance lets you create a subclass that inherits methods and attributes from a parent class. You define a subclass with class Child(Parent):, and the child automatically gains the parent's functionality. To customize behavior, you can override a method by defining one with the same name in the child class. This mechanism enables code reuse and the creation of class hierarchies that model real-world relationships.

All chapters
  1. 1Introduction to Python
  2. 2Variables, Types, and Operators
  3. 3Control Flow
  4. 4Functions
  5. 5Data Structures
  6. 6Object-Oriented Programming
  7. 7Modules, Exceptions, and Advanced Features

Drill it

Reading is not remembering. These come from the Python Programming deck:

Q

What is Python?

Python is a high-level, interpreted programming language known for its readability and simplicity. It supports multiple paradigms including procedural, object-o...

Q

Who created Python and when?

Guido van Rossum created Python, with the first version released in 1991. It was named after the British comedy series Monty Python.

Q

What are the key features of Python?

Python features dynamic typing, automatic memory management, extensive standard library, and cross-platform compatibility. It emphasizes code readability with s...

Q

How do you run a Python script from the command line?

Save the code in a file with .py extension, then run python filename.py in the terminal. Use python3 if Python 2 is also installed.