A class, in the general sense, is a template for something that involves data and operations (functions). An object is an instance of a class, a specific instantiation of the template. Defining a class in Python involves specifying a class name and a collection of variables and functions that belong to that class. The man class that has been referred to so far has only a few characteristics that we know about for certain. It does have a function called walksInto, as one example. A first draft of the man class could be as follows:
def walksInto (aBar):
# code goes here
A function that belongs to a class is generally referred to as a method. This terminology likely refers back to a language devised in the 1970s named Smalltalk. According to the standard for that language, “A method consists of a sequence of expressions. Program execution proceeds by sequentially evaluating the expressions in one or more methods.” In the above example, walksInto is a method; essentially, a method is any function that is part of a class.
Classes can have their own data too, which would be variables that belong to the class in that they exist inside it. Such variables can be used inside the class but should not be accessed from outside.
Looking closely at the simple class man above, notice that it is actually still an abstract thing. In the narrative about a man walking into a bar it was a specific man, as indicated by a variable aMan. A class is really a description of something, in that examples or instances should be created in order to make use of that description. This is correct. In fact, many individual instances of any class can be created (instantiated) and assigned to variables. To create a new instance of the class man, the following syntax could be used:
aMan = man()
When this is done, all of the variables used in the definition of man are allocated. In fact, whenever a new man class is created, a special method that is local to man is called to initialize variables. This method is the constructor, and can take parameters that help in the initialization. Creating a man might involve giving him a name, so the instantiation may be
aMan = man(“Jim Parker”)
In this case, the constructor accepts a parameter, a string, and probably assigns it to a variable local to the class (Name, most likely). The constructor is always named __init__:
def __init__ (self, parameter1, parameter2, …):
The initial parameter named self is a reference to the class being defined. Any variable that is a part of this class is referred to by prefixing the variable name with “self” To make a constructor for man that accepted a name, it would look like this:
def __init__ (self, name):
self.Name = name
When a man is created, the statement would be as follows:
aMan = man (“Jim Parker”)
Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.