Programmazione a oggetti intermedia in Python
Jake Roach
Data Engineer
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
self.height = 0
# This invokes a call to __init__
john = Person("John Casey", 38)
class__init__ è il costruttore, chiamato quando si crea un nuovo oggetto della classeself si riferisce all'istanza corrente della classeclass Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Create an instance of Person
sarah = Person("Sarah Walker", 31)
sarah.age # Retrieve the age instance attribute
self.<attribute-name><object-name>.<attribute-name>class Person:
residence = "Planet Earth"
...
# Accessed without an instance
print(Person.residence)
Planet Earth
class Person:
...
def introduce(self):
print(f"Hello, my name is {self.name}")
chuck = Person("Chuck", 32)
chuck.introduce() # Called on a Person object
$$
self come primo parametroclass Person:
@classmethod
def wake_up(cls):
print("Time to start your day!")
# Calling a class method
Person.wake_up()
$$
@classmethodL'ereditarietà permette di riutilizzare codice tra classi
Employee) eredita tutta la funzionalità della classe genitore (Person)class Person:
def __init__(self, name, age):
self.name
self.age = age
def introduce(self):
print(f"Hello, my name is {self.name}")
class Employee(Person):
def __init__(self, name, age, title):
Person.__init__(self, name, age)
self.title = title
def change_position(self, new_title):
self.title = new_title
lester = Employee("Lester", 26, "Technician")
lester.introduce() # Inherited from Person
print(lester.title)
Hello, my name is Lester
Technician
lester.change_position("Cashier")
print(lester.title)
Cashier
class Employee(Person):
def __init__(self, name, age, title):
# Uses name of the parent class
Person.__init__(self, name, age)
self.title = title
...
__init__()Usare super()
class Employee(Person):
def __init__(self, name, age, title):
# super(), instead of class name
super().__init__(name, age)
self.title = title
...
super(), __init__()selfLa classe figlia implementa in modo nuovo un metodo ereditato dal genitore
class Employee(Person):
...
def introduce(self):
print(f"""My name is {self.name},
I am a {self.title}""")
lester = Employee("Lester", 26, "Technician")
lester.introduce()
My name is Lester, I am a Technician
class Person:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name == other.name
$$
__eq__() sovraccarica ==$$
$$
$$
$$
# Compare two Person objects
chuck = Person("Charles Carmichael")
charles = Person("Charles Carmichael")
print(chuck == charles)
True
Programmazione a oggetti intermedia in Python