INTRO O
PROBLEM SOLVING AND
PROGRAMMING IN PYTHON
(use the Space key to navigate through all slides)

Prof. Andrea Gallegati |
Prof. Dario Abbondanza |

CIS 1051 - INTRODUCTION TO CLASSES

Python types
We have already seen different python types
# an integer number
a = 30
# a floating point number
b = 10.
# a string
text = "Hello world"
# a function definition
def print_data(data):
print(data)
print(type(data))
# Let's print the data
# we just defined
print_data(a)
print_data(b)
print_data(text)
What if we want to define our custom type (object)
Python classes!
By using
class myObject:
# a minimal Class
# without attributes
pass
Minimal definition of a class
MyObject
Still a proper class
Python classes!
By using
class Person:
# Class attribute
# (shared by all instances)
species = "Homo Sapiens"
def __init__(self, name, age):
# Instance attributes
# (specific to each instance)
self.name = name
self.age = age
We can add attributes and methods to a class
This class represents a custom Person object



Python classes!
More about
class Person:
# Class attribute
# (shared by all instances)
species = "Homo Sapiens"
def __init__(self, name, age):
# Instance attributes
# (specific to each instance)
self.name = name
self.age = age
def info(self):
# method (function) to print
# info related to our object
print(f"{self.name} is {self.age} years old")
Functions inside classes are called methods and can use the attributes defined within the class
Indentation is fundamental!
The __init__ method initializes the object based on the arguments passed
- Create a simple class in a module
- Instantiate some objects of that class
- Perform some operations
- Methods can also take as input other objects
Hands-on
Let's do the following together
- Create a new class representing something you like
- Add a few attributes to be initialized in the constructor
- Add a print_info method
- Add a method to change an attribute of the instance
- Add a method that performs some calculations on numeric attributes and displays the result
- Create a main where you instantiate some objects of the newly defined class, and show the use of all the methods implemented
Assignment
python Classes
This was crafted with
A Framework created by Hakim El Hattab and contributors
to make stunning HTML presentations
intro-classes
By Andrea Gallegati
intro-classes
- 89