CLASSES AND INSTANCES
Class objects generally provide the default behavior, they contain a series of attributes which are then data and functions that in the OOP context are called methods. The instances are created, instantiated, starting from the classes and carry out the activities within the programs that we write in Python.
THE STATEMENT CLASS
The class statement is a compound statement that serves to define and create a class object by assigning a name to it. When Python finds the keyword class within a source, which obviously has a header and a suite of instructions, it executes it not by creating the instances of the class but by creating the class object. Let’s see how a class is declared in Python.
class classname (base-classes):
statements
The base-classes if there are are called base classes or superclasses of classname which is the subclass we are defining. If there are several base classes, they must be separated by a comma. If no base-classes are given Python will use object as the base class. Let’s see how the simplest of classes is defined in Python:
class MyClass:
pass
The pass statement has no effect but is a valid statement allowing you to terminate the class definition. This statement can also be used in functions. Having defined nothing after the colon, MyClass will have object as base class.
The above code reads stating that not only is MyClass() a class but it is also an instance of the type class. Type is a predefined type of Python that has as instances all the classes that we are going to define in the programs. Now let’s see how to instantiate the class we just defined. The created instance will inherit all the attributes of MyClass().
INSTANCE AN EXAMPLE CODE CLASS
MyObj = MyClass()
With this assignment, MyObj becomes an instance of the MyClass() class.
ATTRIBUTES OF A CLASS
Attributes can be instance or class. Class attributes are shared by all instances of the class.
CHANGING AN ATTRIBUTE ON AN INSTANCE
If we modify myAttr for example in the m1 instance this will become an instance attribute, leaving the attribute in the MyClass() class and in the m2 instance unchanged.
METHODS OF INSTANCE
myMethod becomes an attribute of the class and is called a method. Methods are also shared among all instances of the class. However, even if the method defined in MyClass() is shared, it must be able to recognize the instance that is calling it. For this reason, methods in Python have a first parameter which by convention is called self and which represents the instance that is making the call.
When the instances m1 and m2 call the method in reality self does not appear, this is because when we invoke for example from m1 MyMethod() Python behind the scenes modifies the invocation by calling the method on the class and passing the object m1 as the first parameter. Obviously if there are more arguments these will be passed too. From our point of view, what occurs is the invocation of myMethod() on the m1 instance.
ADD MORE PARAMETERS AFTER SELF
Let’s see an example in which we pass an additional parameter.
ATTRIBUTES OF INSTANCE
They are created on individual instances of the MyClass() class. Let’s see an example:
If we call printMessage on an instance on which the message attribute has not been initialized, we get an error. This is bad behavior. Let’s see how to avoid it.
THE BUILDER __INIT__
The __init__ method is always called automatically as soon as we build an instance of the class. This constructor always takes self as its first parameter. In this way we are sure that all instances of MyClass() will be initialized with the message attribute. The __init__ method is actually an instance method, which has “self” as its first parameter, as it is invoked on the instance as soon as it has been created by the Python runtime.
CLASS METHODS
They are methods created to be executed on the class object and not on individual instances. These methods are called directly by the class that is passed as a cls parameter within the method. cls has a similar meaning to self, the difference is that self refers to an instance of a class while cls is the class passed as a parameter. Class methods are marked with an @classmethod decorator. Generally these methods are used to instantiate a new class instance, passing parameters other than those required by the constructor. In the example on the side, each time an instance of the class is created, the __init__ constructor is called and the counter is incremented.
STATIC METHODS
Unlike a class method, a static method does not take as its first parameter either an instance such as self or the class parameter cls. It is a method that can be invoked directly on the class that serves to provide a service and does not refer either to the class or to individual instances.
class MyClass(object): counter=0 #servirà a contare quante istanze #vengono costruite sulla classe #counter in quanto definito nel body #della classe è un attributo di MyClass def __init__(self): MyClass.counter+=1 #Ogni volta che creiamo una #nuova istanza, viene chiamato #__init__ e incrementato il contatore @classmethod def istanze(cls): print(cls.counter) #Definiamo un metodo che non è applicabile alle #singole istanze ma alla classe stessa #il decoratore @classmethod serve a questo scopo. #cls per convenzione indica l'oggetto classe m1 = MyClass() m2 = MyClass() m3 = MyClass() MyClass.istanze() #stampa 3
class MyClass(): @staticmethod def somma(a,b): return a+b s=MyClass.somma(20,40) print(s)
IN-DEPTH DISCUSSION OF CLASSES
Classes in Python are a fundamental concept of object-oriented programming (OOP), a paradigm that organizes code around “objects.” These objects are instances of classes, which can be viewed as blueprints (templates) from which objects with defined properties and behaviors can be created.
What is a class?
A class is a structure that defines a set of attributes (variables) and methods (functions) that characterize the objects that will be created from it. Classes are used to model real-world concepts or application logic in a program.
Defining a class
To define a class in Python we use the keyword class followed by the class name (which by convention begins with a capital letter):
class NameClass:
pass # Placeholder, indicating that the class is empty.
Class and instance attributes
Attributes can be class or instance attributes. Instance attributes are bound to a specific object, while class attributes are shared among all instances of the class.
class Studente:
# Attributo di classe
scuola = “Scuola XYZ“
def __init__(self, nome, età):
# Attributi di istanza
self.nome = nome
self.età = età
In the example, scuola is a class attribute, while nome and età are instance attributes.
The __init__ method
The __init__ method is the constructor of a class in Python. It is automatically called when a new instance of the class is created. This method initializes the attributes of the object.
class Studente:
def __init__(self, nome, età):
self.nome = nome
self.età = età
# Creazione di un’istanza della classe
studente1 = Studente(“Mario“, 20)
In this example, when we create studente1, Python calls the __init__ method and assigns nome and età to the object.
Instance methods
Methods are functions defined within a class that operate on the attributes of the instance. The first parameter of each method is self, which represents the instance itself.
class Studente:
def __init__(self, nome, età):
self.nome = nome
self.età = età
def saluta(self):
return f”Ciao, sono {self.nome} e ho {self.età} anni.”
# Uso di un metodo
studente1 = Studente(“Mario“, 20)
print(studente1.saluta())
Inheritance
Inheritance is a concept that allows a new class to be created based on an existing class. The daughter class inherits attributes and methods of the parent class and can override or extend them.
class Persona:
def __init__(self, nome, età):
self.nome = nome
self.età = età
def saluta(self):
return f”Ciao, sono {self.nome}.”
class Studente(Persona):
def __init__(self, nome, età, corso):
super().__init__(nome, età)
self.corso = corso
def saluta(self):
return f”Ciao, sono {self.nome} e studio {self.corso}.”
studente2 = Studente(“Anna“, 22, “Informatica“)
print(studente2.saluta())
In this example, Studente inherits from Persona, but redefines the saluta method.
Encapsulation
Encapsulation is the practice of restricting access to the attributes and methods of an object, protecting them from direct access from outside. In Python, this is accomplished with naming conventions:
-_attribute: designated for internal (private, but not strictly) use.
-__attribute: name mangling to avoid name conflicts in derived classes
class ContoBancario:
def __init__(self, saldo):
self.__saldo = saldo
def deposita(self, somma):
if somma > 0:
self.__saldo += somma
def mostra_saldo(self):
return self.__saldo
conto = ContoBancario(100)
conto.deposita(50)
print(conto.mostra_saldo()) # Output: 150
In this example, __saldo is protected from direct access, allowing control over how it is modified.
Leave A Comment