Sunteți pe pagina 1din 24

PROGRAMMING WITH PYTHON

a.y. 2018-2019

Lesson 14
Classes, attributes, methods

SEDIN
IT Education Services Center
2

Objectives of the lesson


• Understand the concepts of class, attribute and method
• Learn to access files
3

Objects
• Python supports different types of data:
1946 3.1415926535 "Hello World!" [1, 5, 7, 11]

• Each of them is an instance of an object, and each object has:


1. a type to which it belongs
2. an internal representation of the data (in machine language)
3. a set of procedures (method) used to interact with the object

• Every instance is a particular object belonging to a specific type


- 1946 is the value of an instance of type: int
- a = "Hello World!"  a is an instance of str (string) type

Everything in Python is an object. And objects can be defined by users.


4

Objects, classes and instances


• An object is an abstract element characterized by attributes (how it is
made) and methods (how we can modify and use it)

• A class is the abstract description of an object. It represents the «family»


or set of objects of a certain type

• An instance indicates a specific case of a class. It is a specific set of


values assigned to the attributes of the class

name
Person
last_name John
Snow

Definition of an object, Group of objects of


Instance of an object
i.e. of its class the same class
5

Classes of objects
• Before creating an object it is necessary to define it
• Assuming to be able to create an object through a «mold», the definition
of the object represents the creation of the mold

• The creation through a mold originates identical objects, which can be


customized thanks to their attributes

• Similar objects created in this way will originate a «class of objects»


• The definition of an object starts by defining the related class
6

Creation of a class
• To create a class you need to give it a name and define its attributes
and/or methods

• All instances of the class inherit attributes and methods of the class to
which they belong

• Attributes and methods inherited from individual instances can be


changed at a later time. Furthermore, each instance can have additional
or different attributes and methods with respect to the parent class
7

Creation of the class Person


definition of the class
name of the class DEFINITION OF A CLASS OF OBJECTS

class Person():
''' Class of objects of type: Person '''
attribute
attribute
attribute
attributes of the class

def method(self):
instruction
instruction
method of the class
8

Attributes of a class
• They allow to customize each single object of the class
• They can be Python built-in types (i.e.: int, float, list) or other objects
• They can be defined directly in the class (with an assignment, as shown
here below), but they are usually defined with a special method called
constructor method

class Person():
name = "" # str, initially null
last_name = "" # str, initially null
height = 0 # int, cm, initially zero
weight = 0.0 # float, kg, initially zero
9

Constructor method __init__


• It is the method that Python search in the class when it has to initialize the
state of an object
• It can include the definition of the attributes and of any other feature and
option needed to the objects of the class, like: call of functions, opening of
files, access to databases etc.
• The syntax follows the same rules used when defining a function, with the
parameters (mandatory or optional) that are used to initialize the attributes,
specified in parentheses
• There must be at least one parameter – conventionally named self – that
represent the reference to the name of the instance that will be created
10

Creation of __init__ method


initialization method

required parameter
self parameter optional parameters

class Person():

def __init__(self, nat, name="", last_name=""):


self.name = name
self.last_name = last_name
self.nationality = nat
self.height = 0
self.weight = 0.0

Initialization of attributes not defined as parameters


(see examples of use in following slides)
11

Creation of instances of the class Person

method that creates an instance of


the class «Person» with attributes
specified as parameters
name of the instance
INSTANCE AN OBJECT STARTING FROM ITS DEFINITION

mary esteban juliette


mary = Person('english')

esteban = Person('mexican')

juliette = Person('french')
12

Interact with object attributes


• To access a specific object, we must use the name of the instance
• To define the value of an attribute we can use:
Instance_Name = Class_Name(val_1, val_2, …)
(only when the attribute has been defined as a parameter of the constructor method __init__)

Instance_Name.Attribute_Name = value mary


(for attributes not defined as parameters. It can also be used for
those attributes defined as parameters in the __init__ method)
.name 'Mary'
.last_name 'White'
mary = Person('english', 'Mary', 'White')
.height 183
mary.height = 183 .weight 70.6
mary.weight = 70.6 .nationality 'english'
13

Copy of objects
mary mary2
• A simple assignment cannot be used to copy objects
• mary2 = mary .name 'Mary'
- it will not create a copy of mary in mary2 .last_name 'White'
- it will define a second variable, mary2, addressing the same memory area .height 183
of mary, then to the same object .weight 70.6

- changing the mary2 object is equivalent to changing the mary object


mary3

• mary3 = copy.copy(mary)
- uses the copy() function of the copy library
.name 'Mary'
- the library must first be imported (import copy)
.last_name 'White'
- performs a copy of the object in memory (mary) in another memory area,
.height 183
and assigns the memory address to access the object to a new variable
(mary3) .weight 70.6
14

Methods
• They are not variables/objects that contain a PERSON

.name
value, but procedures that execute instructions
.last_name
.height
• They can return a value thanks to the return .weight
statement .BMI ()

method for the calculation of


• They have at least one parameter: self the Body Mass Index (BMI)

• They are invoked with the same notation of the attributes:

Instance_Name.Method_Name(parameters)
15

Methods of the class


class Person():

def __init__(self, nat, name="", last_name=""):


self.name = name
self.last_name = last_name
self.nationality = nat
self.height = 0
self.weight = 0.0

mandatory parameter for all methods: in


this case, it represents the Person object
self.weight and self.height identify the attributes of the object

def BMI(self):
bmi_value = self.weight / (self.height/100)**2
return bmi_value

keyword to define keyword to allow a formula for the calculation of the body mass
a method method to return a value index, which will be returned by the method
16

Special method __str__


• It constructs and returns a string representing the state of the object
• It is called by built-in functions print, str and format
• It has no arguments (besides self) and must have a return statement

class Person: mary

def __str__(self):
t = (self.name + " " +
self.last_name + " (" + .name "Mary"
str(self.height) + "cm, " + .last_name "White"
str(self.weight) + .height 183
"kg, has a Body Mass Index of " +
.weight 70.6
str(round(self.BMI(), 1)) + ')')
return t .nationality 'english'

>>> print(mary)
Mary White (183cm, 70.6kg, has a Body Mass Index of 21.1)
17

Hierarchies and Inheritance


• parent class (superclass) object
name
last_name
• child class (subclass) height
weight
Person BMI()
- inherits all data and methods of the parent class __init__()
__str__()
- adds more info and methods
- overwrites methods badge_id Student Professor id
hail() hail()
__init__() __init__()

class Person():
pass
class Student(Person): subclass of the objects category
pass
class Professor(Person):
pass superclass for Student and Professor

subclasses of Person
18

Access to files
To open a file in Python we use the open function, that creates a file object
to which is associated the specific file we want to open.
In Python the built-in function to access files is open()
• it opens a file and returns an file
directory
file
(text)
file
(binary)

object of type file 110101011101


0001010101
01010010101
01011111000
000101

• if the file cannot be opened, binary

an error is raised File System


block
110101011101000101
01010101001010101
011111000000101111
111100000000011111

• Opening a file involves creating


1110

Operating System
a variable to which the object
should be associated
19

The built-in function open()


optional argument: it specifies how the file should be
opened (in reading or writing mode). If the argument
• The syntax: is omitted, the file is opened as read-only
open(file, mode)
mandatory argument: a text string that specifies the
name of the file, including its complete path in the disk

• To open a file in read/write mode:


f = open('G:\Data\students.txt', 'r+')
opens the file in both read and write mode.
• To read the content of a text file:
row = f.readline()
data.txt
print(row)
first row¶
Mario Rossi (183cm, 81.5kg)\n second row¶
third row¶

• To close (and save) a text file: EOF
f.close()
20

Reading methods
The content of a file can be read entirely or line by line:

• The read method reads the contents of the entire file


• The readline and readlines methods read the content line by line

f = open('students.txt')

row = f.readline()
while row != '':
print(row)
row = f.readline()

f.close()
21

Writing in a text file


f = open("students.txt", "w")
opens the file in write mode. If the file
f.write("Anna Corti\n") already exists, when it is opened the data
contained in it is deleted. If the file does
f.write("Salvo Brandi\n") not exist, it is automatically created

f.write("Nina Ferdi\n")
f.close()
to end a line in the text file, the
"new line" character is needed

f = open("students.txt", "a")
f.write("Lola Manno\n") opens the file in add or append mode. Python
positions itself at the end of the last line of the
file, therefore all the data Python writes in the
f.close() file is added to the end of the document
22

Tools to learn with today’s lecture


• Understanding the meaning of "object"
• Know the difference between "class", "object" and "instance"
• Learn how to define the attributes of an object
• Create object classes, instantiate new objects, copy and modify existing
objects
• Define procedures that can interact with objects: methods
• Know the concept of "inheritance" of the classes
• Learn to read and write on files thanks to the use of the built-in function:
open( ), and via specific methods
23

Files of the lesson


In the zip file 30424 ITA - 28 - Lesson 14.zip you will find these files:
• 30424 lesson 14 slides.pdf: these slides
• Example_lesson_14.py: file of the lesson
• Exercises 30424 lesson 14: exercises on the content of the lesson
24

Book references
Learning Python:
Chapters 12, 10.1, 10.2, 10.3

Assignment:
Exercises of lesson 14

S-ar putea să vă placă și