Sunday, 5 April 2020

class composition in python with example

Composition is a concept that models a has a relationship. It enables creating complex types by combining objects of other types. This means that a class Composite can contain an object of another class Component. This relationship means that a Composite has a Component.

Example:

class Garage:
    def __init__(self*cars):
        self.cars = cars

    def __str__(self):
        return (f"Total {len(self.cars)} cars in the Garage")

class Cars:
    def __init__(selfnameyear):
        self.name = name
        self.year = year

    def __str__(self):
        return ("{} is moving to Garage in {}".format(self.name, self.year))


car = Cars("Ferrari""2019")
car2 = Cars("Rolls""2020")
car3 = Cars("Benz""2021")
garage = Garage(car, car2, car3)

print(car)
print(car2)
print(car3)
print(garage)

Output:
Ferrari is moving to Garage in 2019
Rolls is moving to Garage in 2020
Benz is moving to Garage in 2021

Total 3 cars in the Garage

3 comments:

Expense Handler Application with advance technologies

Budget Planner  One of the application developed with Ionic 4 and Python-Flask.  Ionic 4 code:  https://github.com/logeshbuiltin/Expense...