Python Lessons – 7.1 Classes

Python lessons - 7.1 Classes
Scrivi una didascalia…

Classes

So far you have seen programming by following two different paradigms:

  • imperative: using declarations, cycles, functions
  • functional: pure functions, high-order functions and recursions

Another programming paradigm is the object-oriented programming (OOP).

Objects are created using classes that are the centerpiece of all object-oriented programming.

A class defines an object and uses the class clause to indicate it. The correct way to define a class is as follows:

Here, you can see an example:

if you run this program, you get:

All methods within a class must have self as the first argument. At the time of the call then this will not be explicitly called, but Python will implicitly.

Instances of a class have attributes, these are nothing but parts of data associated with it. The attributes of a class are accessible by a dot between the object name and the name of its attribute.

objectname.attribute

The __init__ method

In the previous case, in the definition of a class, you have defined a method called __init __(). This method is the most important method within a class. This method is called when a class is created, that is, when the class name is called as if it were a function (object creation).

The __init__ method is often called a constructor, it accepts all the other methods of a class, the self argument, and then all the class attributes.

Methods

Classes can have other methods besides the constructor. However, everyone must have self as their first argument. Methods such as attributes are also called via the . referencing.

objectname.methodname()

Here is an example:

if you run it, you get:

Class attributes

Classes can also have class attributes, which are variables that are defined at the time of creation. So their value is already defined when the object is instantiated.

if you run it, you get:

Class attributes make sense when the value they contain is valid for all objects belonging to that class.

If you try to access a non-existent attribute, you get an AttributeError exception.

⇐ Go to Python Lesson 6.8 – The itertools module

Go to Python Lesson 7.2 – Inheritance ⇒

Leave a Reply