(use the Space key to navigate through all slides)
Prof. Andrea Gallegati |
Prof. Dario Abbondanza |
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)
By using
class myObject:
# a minimal Class
# without attributes
pass
Minimal definition of a class
MyObject
Still a proper class
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
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
A Framework created by Hakim El Hattab and contributors
to make stunning HTML presentations