Learning Python: Part 4: Objects

Learning Python

Python is a general-purpose interpreted programming language. It emphasizes readability through the use of whitespace and supports multiple programming paradigms such as functional and object-oriented models.


Objects

One of the dominant programming models is the object-oriented model. This treats complex processes and projects as a series of objects that are defined through their relationships to each other.

An object is considered the smallest unit in a relationship. It has properties (aspects that describe it) and functions (how it communicates with other objects).

Defining Objects

Objects are defined in Python through the keyword class. This marks some code as a “blueprint” for a new object. When it is created, the new object will have the same properties and functions described in the object definition.

Like functions, an object is defined using the keyword, the name of the object, and then a colon. Code “under” the object are part of it.

Constructors

In the object-oriented programming model, a constructor is a function that “constructs” an object. As a function, it allows objects to have data sent “into” it in order to initialize values or otherwise prepare other code.

__init__()

Python did not start as an object-oriented language. One way support for the model has been added to the language over the years is through the __init__() function. It “initializes” an object.

Self

To prevent confusion when using different variables, the keyword self was introduced to describe properties of an object.

Use of the self keyword uses the period notation. This tells Python that the variable name that follows it is part of the object. For example self.name would describe a variable name that is part of the current object.

Functions that are part of an object have their first parameter as self. This allows functions to reference the object they are a part of and use its properties.

Creating Objects

New objects are created through using the name of the object and its parameters. This calls its constructor and builds a new version of it.

Once created, objects can reference the functions that are a part of in the same way of using the self keyword: period notation.

Play with the example on Repl.it!