Méthodologie de la Programmation
Notes de cours - Séance IV

Setters et getters

class Animal(object): def __init__(self, name, age) : self.name = name self.age = age def get_name(self): return self.name def get_age(self): return self.age def set_age(self, new_age): self.age = new_age def set_name(self, new_name): self.name = new_name

Getters et setters avec avec les décorateurs

class Animal(object): def __init__(self, name, age): self.__name = name self.__age = age def __str__(self): return "animal: " + str(self.__name) + ":" + str(self.__age) @property def name(self): return self.__name @property def age(self): return self.__age @property def nimp(self): return self.__age * 10 @name.setter def name(self, name): self.__name = name @age.setter def age(self, age): self.__age = age
animal = Animal("foo", 42) animal.name = "bar" print(animal.nimp) # 420 print(animal.name) # bar

Héritage

# On hérite de la classe Animal class Humain(Animal): # Override du constructeur de Animal def __init__(self, name, age): Animal.__init__(self, name, age) self._amis = [] @property def amis(self): return self._amis @amis.setter def amis(self, ami): if ami not in self._amis: self._amis.append(ami) # Implémentation de nouvelles méthodes def difference_age(self, other): diff = abs(self.age - other.age) print(diff, " années de différence") def speak(self): print("hello word !")
a = Humain("test", 42) a.speak() # hello world ! a.amis = "foo" print(a.amis) # ['foo'] print(a.age) # 42 a.age = 12 print(a.age) # 12

super()

class Humain(Animal): def __init__(self, name, age): # Appelle le constructeur de Animal super().__init__(name, age) self._amis = []

Héritage multiple

class GroundVehicle(object): def drive(self): print("Drive !") class FlyingVehicle(object): def fly(self): print("Fly !") class FlyingCar(GroundVehicle, FlyingVehicle): pass
fc = FlyingCar() fc.drive() # Drive ! fc.fly() # Fly !