This lesson is being piloted (Beta version)

Object Oriented Programming in Python: Glossary

Key Points

Objects in Python
  • Anything that we can store in a variable in Python is an object

  • Every object in Python has a class (or type)

  • list and numpy.ndarray are commonly-used classes; lists and arrays are corresponding objects

  • Calling the class as a function constructs new objects of that class

  • Classes can inherit from other classes; objects of the subclass are automatically also of the parent class

Writing classes
  • Classes in Python are blocks started with the class keyword

  • Method definitions look like functions, but must take a self argument

  • The __init__ method is called when instances are constructed

  • Adding a class in parentheses after a class definition indicates that the new class is a subclass of the bracketed class (parent class).

  • The subclass inherits all of that parent class’s attributes and methods.

  • Defining a method with the same name as one of the parent class’s overrides it.

  • Use super() to access parent classes and their methods.

Decorators, class methods, and properties
  • A decorator adds functionality to a class or function. To use the decoratorname decorator, add @decoratorname one line before the class or function definition.

  • Use the @classmethod decorator to indicate methods to be called from the class rather than from an instance.

  • Use the @property decorator to control access to instance variables

Special methods
  • Implement methods like __eq__, __add__, and __gt__ to allow operations such as arithmetic and comparisons.

  • Implement __repr__ to get more meaningful printouts when you output an object.

  • Implement methods like __len__, __iter__, and __reversed__ to make instances of a class behave like a collection or iterable.

  • Implement the __call__ method to make instances of a class callable like functions.

Duck typing and interfaces
  • Provided a class exposes all required functionality for an operation to work, Python allows it.

  • Only use inheritance to express relationships where the subclass is the same kind of thing as the superclass.

  • Implementing interfaces and adding functionality with composition can be better alternatives to inheritance in some cases.