Wesh les gars,
Comme l'indique le titre, je veux transformer une inheritance en composition. Je sais que mon problème est la ligne "self.agency = All_Clients.__init__(agency)", mais aucune idée comment récupérer l'attribut de l'autre classe quand il s'agit d'une composition.
ça c'est la version inheritance
Et ça c'est une tentative de composition
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 class Client: def __init__(self, agency): self.agency = agency def printout(self): return f'{self.agency}' class Buying_Client(Client): def __init__(self, fullname, amount, agency): super().__init__(agency) self.fullname = fullname self.amount = amount def printout(self): parent = super().printout() return f'{self.fullname}, {self.amount}, {parent}' variable_1 = Buying_Client("John DOE", "$100", "NYC") variable_2 = Buying_Client.printout(variable_1) print(variable_2)
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 class All_Clients(object): def __init__(self, agency): self.agency = agency def printout(self): return f'{self.agency}' class Buying_Client(object): def __init__(self, fullname, amount, agency): self.fullname = fullname self.amount = amount self.agency = All_Clients.__init__(agency) def printout(self): other_class = All_Clients.printout() return f'{self.fullname}, {self.amount}, {other_class}' variable_1 = Buying_Client("John DOE", "$100", "NYC") variable_2 = Buying_Client.printout(variable_1) print(variable_2)
Partager