Download presentation
Presentation is loading. Please wait.
1
Programmazione ad alto livello con Python
Lezione 4: Programmazione orientata agli oggetti, classi, istanze e metodi. Dr. Gabriele Mencagli Dipartimento di Informatica Università di Pisa 01/12/2018
2
Informazioni Dr. Gabriele Mencagli
Dipartimento di Informatica, Università di Pisa Stanza 287. Ricevimento su appuntamento (mandare una ) web: Organizzazione: corso introduttivo. 16 ore di didattica frontale, 14 di esercizi individuali in laboratorio Durata: 2 mesi Modalità di esame: progetto finale di complessità variabile Importante gli homework!!! (tipicamente uno per settimana) 01/12/2018
3
Topics In this lecture we study:
Brief introduction to Object Oriented Programming; How to define classes, attributes and methods; How to handle errors and exceptions; Use Generators and Iterators in our code. 01/12/2018
4
Object Oriented Programming
So far we have studied Python as a procedural language with only procedure/functions to encapsulate and reuse our code. Python is more…it provides the Object Oriented Paradigm (OPP) as other languages like C++, C#, Java an so forth. What is a class and an instance of that class? Classes describe concepts (data or operations) of the domain of interest; Classes can be instantiated several times. Each instance is an object of that class. Each instance has proper internal data (variables); Methods are procedures/functions associated with classes. Each class has a proper set of methods. Therefore, for each istance of a class we can invoke the corresponding methods. Methods allow programmer to read and modify the data of an object. In the next few slides we recall basic concepts of OOP programming! 01/12/2018
5
What is a Class? Real-life objects are represented as software objects. Objects combine characteristics (attributes) and behaviors (methods). Car ATTRIBUTES: make model color wheels seats autobody motor METHODS: start() drive() stop() honk() 01/12/2018
6
What is an Object? Classes are blueprints/designs for objects.
Creating objects using classes: we instantiate objects. Objects are also called instances of a class. Objects of the same class have the same basic structure, but they can differ in various respects (different values of the attributes!) 01/12/2018
7
Inheritance Some different objects share characteristics / behaviors. Inheritance saves us from writing the same code over and over again. If Classes2 extends Class1, all the object of Class2 are also objects of Class1. They have all the operations and attributes of the objects of Class1 but also more! 01/12/2018
8
Goals of OOP What are the goals of the Object Oriented Paradigm? A brief list is the following: Encapsulation: dividing the code into a public interface, and a private implementation of that interface; Inheritance: the ability to create subclasses that contain specializations of their parent classes. Polymorphism: The ability to override methods of a Class by extending it with a subclass (inheritance) with a more specific implementation (inclusion polymorphism) All these aspects and their specific characterization in Python will be studied in this lecture and in the next one (lect. 4 and 5). 01/12/2018
9
Topics In this lecture we study:
Brief introduction to Object Oriented Programming; How to define classes, attributes and methods; How to handle errors and exceptions; Use Generators and Iterators in our code. 01/12/2018
10
Defining a class A class is a blueprint for a new data type with specific internal attributues (in this case it is similar to a struct in C) and internal operations (methods). To declare a class in Python the syntax is the following: A very simple example. Let us define a class Point with two internal variables (instance attributes/variables) representing the coordinates: class name: statements 01/12/2018
11
Accessing instance attributes
Instance attributes can be declared directly inside class (as shown in this example) or in constructors (more common). We will see what a constructor is! The first statement of the main p1=Point() is the call to the implicit constructor of the class. P1 is an instance (object of class Point)! 01/12/2018
12
Accessing instance attributes (2)
As obvious, each instance of the same class has the same number and type of instance attributes. However, each object has its own set of attributes with different values than other istances of the same class. Objects of the same class can have different values of their attributes! P1 and P2 are two instances of class Point. They have instance attributes X and Y. For the first point P1 the values are (2,-5), for the second point P2 (3, 10). 01/12/2018
13
Adding instance attributes (3)
Python objects are dynamic. You can add instance attributes any time! Let us consider this example: The instance attribute z has been added to the object p1 (and only to that instance of class Point). This is an important difference with other OOP programming languages like Java and C++! 01/12/2018
14
Instance methods A class defines the attributes of each instance but also a set of methods that manipulate the attributes (read and modify them). We call them instance methods. Inside the scope of a class definition we can define several methods that are functions/procedure defined according to the following syntax: Self must be the first parameter to any object method represents the "implicit parameter" (this in Java); A method must access the object's attributes through the self reference. This is different from other object oriented programming languages like C++ and Java in which the reference to the object (this) can be implicitly used in any use of a local variable of the instance. def name(self, parameter, ..., parameter): statements 01/12/2018
15
Instance methods (2) This is the class Point with three instance methods. We show how to create objects and how to invoke their methods: 01/12/2018
16
Obj.operation1(actual parameters…)
Instance methods (3) This is the output of the previous script: Some aspects are particularly important and should be analyzed deeply: The self parameter of the method is special. It must be used in the declaration of the instance method and inside its code to refer to the instance of the object and to access its local variables: The self parameter must not be passed to the invokation of the instance methods. If we need to invoke an instance method operation1 on the object obj the syntax is: Obj.operation1(actual parameters…) 01/12/2018
17
Calling instance methods
Let us denote by obj and object of class Class. We want to invoke an instance method operation of this class. A programmer can call the methods of an object in two ways (the value of self can be an implicit or explicit parameter): obj.operation(paramters…) – the parameter self is passed implicitly. Class.operation(obj, parameters…) – the parameter self is passed explicitly. The two invokations of the method set_location are equivalent in Python. 01/12/2018
18
Encapsulation Python does not really have encapsulation or private fields but relies on caller to "be nice" and not mess with objects' contents. Attributes of an object should be ’hidden’ from manipulations from ’outside’. Attributes should be modified using code that was written within the class definition ensures that the state of the object is always valid. 01/12/2018
19
Constructors A constructor is a special instance method of a class with the name __init__. It allows to create a new instance of the class with specific values of its attributes: In this example we create an instance of a point. In the statement p1=point() we create an instance p1 of the point: “this is an implicit invokation of the constructor of the class”! def __init__(self, parameter, ..., parameter): statements 01/12/2018
20
String representation
It is often useful to have a textual representation of an object with the values of its attributes. This is possible with the following instance method: This is equivalent to Java's toString (converts object to a string) and it is invoked automatically when str or print is called. def __str__(self): return string 01/12/2018
21
Private attributes and methods
Actually in Python is possible to declare private instance attributes and methods, i.e. instance attributes and methods that can be used only from a code inside the class! All the attributes and methods with a name starting with __ (except the ones with a name also finishing in __) are private! Example (the interpreter throws an error – id can not be used outside the class): 01/12/2018
22
Complete point class This is the complete Point class. Please note that the creation of the attributes X and Y can be performed in the constructor instead of just after the line “class Point”: 01/12/2018
23
__truediv__(self, other)
Special methods Method overloading: you can define special instance methods so that Python's built-in operators can be used with your class. See also: for further information about this topic! Many other special methods exist! Study them Binary Operators Operator Class Method - __sub__(self, other) + __add__(self, other) * __mul__(self, other) / __truediv__(self, other) Operator Class Method == __eq__(self, other) != __ne__(self, other) < __lt__(self, other) > __gt__(self, other) <= __le__(self, other) >= __ge__(self, other) Unary Operators - __neg__(self) + __pos__(self) 01/12/2018
24
Special methods (2) Let us exemplify this concept with our Point class. We define a method to compute the sum between two points. We sum the corresponding coordinates to produce a new point. The result is p3=(6, -2). 01/12/2018
25
Garbage collector Python's memory allocation and deallocation method is automatic. The user does not have to preallocate or deallocate memory by hand as one has to when using dynamic memory allocation in languages such as C or C++. Destructors are a very important concept in C++, where they're an essential ingredient. In Python they are less important because we can rely on an automatic garbage collector. However, destructors still exist in Python because there are other resource (sockets, files and buffers) that need to be freed when an object is done with them. The destructor of an object is a special method of the corresponding class with the name __del__(self). The destructor is invoked when the Garbage Collector destroys the instance (i.e. when no reference to the object, the object can not be accessed). 01/12/2018
26
Garbage collector (2) This is an example of the __del__ method used with a class instance. We print a message when the object is created and destroyed by the Garbage Collector (GC). The program outputs the message “ID born” and “ID died”. The destructor is automatically invoked by the GC when the program exits from the function, because no reference to the instance of FooType exists in the program. The __del__ method can be explicitly invoked using the statement “del ft”. 01/12/2018
27
Class attributes Each object has its own set of attributes with specific values different from the ones of other istances of the same class. We called these variables “instance attributes”. In Python we can have class attributes not corresponding to a specific instance but to the class! Their usage is as follows: Outside the class they are used by referring to the class name instead to the reference of a particular object: “classname.attribute”; Inside an instance method they are referred by using the syntax: “self.__class__.attribute” or “classname.attribute”. Example: we have a class “Node” with an instance attribute “name”. We want to keep tracking on how many times this class is instantiated. We use a class attribute “count”. 01/12/2018
28
Class attributes (2) It is worth noting that class attributes can be used as instance attributes just after the “class name:” statement. However, their usage is different. If we access them using the name of the class we are using the attribute as a class attribute. Example: We can not change the value of a class attribute in an instance method. This creates a new instance attribute with the same name of the class attribute! 01/12/2018
29
Static and Class methods
Sometimes we need to process data associated with classes instead of instances. Example: keeping track of instances created or instances cureently in memory. This data are associated to class. It is worth noting that simple functions written outside the class can suffice for this purpose! However, the code is not well associated with class, cannot be inherited and the name of the method is not localized. Hence, Python offers us static and class methods. In the next slides we will see examples of static and class methods. 01/12/2018
30
Static methods Static methods are simple functions with no self argument. They are nested inside class but they cannot work on the instance attributes and methods of the object (they cannot access the variable sender in the example) They can be called through both the class and any instance of that class! Benefits of static methods: they allow subclasses to customize the static methods with inheritance. Classes can inherit static methods without redefining them. The output of the program is “2” for all the print statements. 01/12/2018
31
Class methods They are similar to static methods but they have a first parameter which is the class name. The are simply decorations that indicate that the following methods are static or related to the class. 01/12/2018
32
Aggregate objects We can aggregate objects. Example an instance of class Account refers to an instance of class Person (the owner of the account): An instance variable can be a complex object, non only a primitive value. 01/12/2018
33
Topics In this lecture we study:
Brief introduction to Object Oriented Programming; How to define classes, attributes and methods; How to handle errors and exceptions; Use Generators and Iterators in our code. 01/12/2018
34
Errors and Exceptions Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python. Example: The parser repeats the offending line and displays the earliest point in the line where the error was detected. Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal: Most exceptions are not handled by programs. 01/12/2018
35
Errors and Exceptions (2)
Most exceptions are not handled by programs, however, and result in error messages as shown here: The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are ZeroDivisionError, NameError and TypeError. 01/12/2018
36
Handle exceptions It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control-C or whatever the operating system supports). Note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception. Exception handling is performed by the try-except construct. The behavior of this construct is explained in the following slide. 01/12/2018
37
Try-Except construct The try statement works as follows:
First, the try clause (the statement(s) between the try and except keywords) is executed; If no exception occurs, the except clause is skipped and execution of the try statement is finished; If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement; If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above. A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed: Without any name after except we handle all the possible exceptions raised in the try block. except (RuntimeError, TypeError, NameError): pass 01/12/2018
38
Try-Except-Else construct
The try-except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example: The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try-except statement. When an exception occurs, it may have an associated value, also known as the exception’s argument. The presence and type of the argument depend on the exception type. 01/12/2018
39
Raising exceptions The raise statement allows the programmer to force a specified exception to occur. For example: The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception). If you need to determine whether an exception was raised but don’t intend to handle it, a simpler form of the raise statement allows you to re-raise the exception. 01/12/2018
40
Raise exceptions (2) This is an example in which the programmer raises an exception when a specific condition is satisfied. In this case the condition is that the number is not positive. NameError is a built-in name for expections in Python. They are raised when a local or global name is not found. In this case we use this exception type for other reasons. Better is to introduce our exception definition!. We will see how to do it in the next slides! 01/12/2018
41
Exception arguments The except clause may specify a variable after the exception name (or tuple). The variable is bound to an exception instance with the arguments stored in instance.args. For convenience, the exception instance defines __str__() so the arguments can be printed directly without having to instance.args. If an exception has an argument, it is printed as the last part (‘detail’) of the message for unhandled exceptions. 01/12/2018
42
Finally The try-except command has an optional finally field that includes a code that must always be executed, either any exception has been araised in the try block either the execution not raise any exeception. 01/12/2018
43
User-defined exceptions
Programs may name their own exceptions by creating a new exception class. Exceptions should typically be derived from the Exception class. For example: The first row: class MyError(Exception): between brakets we have the name of the super class (MyError derives from Exception). We will see inheritance in the next lecture. Exception classes can be defined which do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception. 01/12/2018
44
Topics In this lecture we study:
Brief introduction to Object Oriented Programming; How to define classes, attributes and methods; How to handle errors and exceptions; Use Generators and Iterators in our code. 01/12/2018
45
What are iterators? An iterator is an object which allows a programmer to traverse through all the elements of a collection (iterable object), regardless of its specific implementation. In Python they are used implicitly by the FOR loop construct. Python iterator objects required to support two methods: __iter__ returns the iterator object itself. This is used in FOR and IN statements. next method returns the next value from the iterator. If there is no more items to return then it should raise StopIteration exception. Remember that an iterator object can be used only once. It means after it raises StopIteration once, it will keep raising the same exception. Example: >>> lista= [1,2,3] >>> it = iter(lista) >>> it <listiterator object at 0x00A1DB50> >>> it.next() 1 2 3 >>> it.next() -> raises StopIteration for elemento in [1, 2, 3]: print elemento 01/12/2018
46
Iterator objects This example shows how to create a class which is an iterator. The iterator can be used in a FOR loop! Output: ! Similar to range but slightly different… 01/12/2018
47
Iterator objects (2) Using the iterator in the FOR loop example we saw, the following example tries to show the code behind the scenes: Output: ! (the same of the previous slide) 01/12/2018
48
Generators Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield statement whenever they want to return data. Each time the next() is called, the generator resumes where it left-off (it remembers all the data values and which statement was last executed). An example shows that generators can be trivially easy to create. Anything that can be done with generators can also be done with class based iterators as described in the previous section (not vice-versa). What makes generators so compact is that the __iter__() and next() methods are created automatically. Another key feature is that the local variables and execution state are automatically saved between calls. This made the function easier to write and much more clear than an approach using class variables like self.index and self.data. 01/12/2018
49
Generators (2) In addition to automatic method creation and saving program state, when generators terminate, they automatically raise StopIteration. In combination, these features make it easy to create iterators with no more effort than writing a regular function. The output is: ! 01/12/2018
50
END 01/12/2018
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.