Compared to programming in procedural languages like C and Fortran 77, Object Oriented Programming (OOP) is a very different—and some would argue, more natural—way to write codes. Instead of asking the question, What does this program do?, the object-oriented approach invites you to ask: What is the world created by this program? What objects are in it? How do they interact?

OOP in Python covers a wide spectrum of topics. However, our goal in this section isn’t to make sure you can write a sophisticated object-oriented program. It is to make sure you understand, in the context of Python:

  • What is OOP?
  • What is an object?
  • How is it related to a class?
  • How do I create an object?
  • What can I do with an object?
OOP and objects

Object-oriented programming does not treat data as existing independently or in isolation, but rather in terms of objects, which are entities that combine data together with the possible actions that can be taken on the data. An object must therefore encompass both state (data) and behavior (instructions).

Classes, attributes, and methods

Accordingly, an object’s type definition involves much more than, say, a bare description of how certain fields are laid out in memory. Class is the special name given to the type of an object. Formally, it is the abstract data type of an object. In general, a class’s definition includes both attributes and methods. Attributes are data associated with the class, and methods are the procedures (or functions) of the class. (Technically, in Python one says that classes specify “data attributes” and “method attributes”, but the idea is the same, so we will use the simpler, generic terms.)

Instances

When an object is created, it has a type that identifies it as belonging to a certain class. The object is said to be an instance of that class. A class can therefore be thought of as a constructor of objects, while instances are nothing more than the particular objects that have been constructed by a particular class.

Any instance will:

  • Definitely possess the methods and attributes defined for its class
  • Optionally possess extra, new attributes and methods which are specific to the instance
Python objects

In Python, everything is an object. This includes simple things like numbers, as well as other things that you might not think of as having attributes and methods, like functions.

Moreover, all Python attributes and methods are public, which means they are accessible outside of the program unit in which they are defined (a module file, typically). It's convenient that so many attributes of an object are accessible — but is a different behavior than what finds in some other languages supporting OOP.

 
©  |   Cornell University    |   Center for Advanced Computing    |   Copyright Statement    |   Inclusivity Statement