Home > Software engineering >  Passing instances to object vs adding instance as attribute later
Passing instances to object vs adding instance as attribute later

Time:11-03

I have a case where my object sometimes has an associated object and other times does not. e.g. my car sometimes has cruise control, and other times does not.

There are two patterns I am debating between - passing an instance, or adding this later. I would like to understand which is the best option (or if there is a better option)

Should I be going this approach:

class Car():
    def __init__(self, brand, satnav):
        self.brand = brand
        self.satnav = Satnav()

class Satnav():
    def __init__(self, brand=None):
       self.brand = brand

my_car = Car('ford')

or this one:

class Car():
    def __init__(self, brand):
        self.brand = brand

class Satnav():
    def __init__(self, brand=None):
       self.brand = brand

my_car = Car('ford')
my_car.satnav = Satnav('tomtom')

CodePudding user response:

if you are struggling with such philosophical decision... then you should opt for decorators! They are flexible and purpose oriented: for example car2car_with_nav create a child-class of Car, called WithSatNav, with an attribute satnav. So your original class will be untouched and accessible but you gather a new class which keeps track of cars with navigator.

def car2car_with_nav(satnav_brand):
    return lambda cls: type(f'{cls.__name__}WithSatNav', (cls,), {'satnav': Satnav(satnav_brand)})
    
class Car:
    def __init__(self, brand):
        self.brand = brand

class Satnav:
    def __init__(self, brand=None):
       self.brand = brand


car_with_nav = car2car_with_nav('tomtom')(Car)

print(car_with_nav)
print(car_with_nav.satnav.brand)
print(car_with_nav('ford'))
print(car_with_nav('ford').brand)
print(car_with_nav('ford').satnav.brand)

Output

<class '__main__.CarWithSatNav'>
tomtom
<__main__.CarWithSatNav object at 0x7fa8d82fd0d0>
ford
tomtom

CodePudding user response:

You can add satnav as an attribute of car and assign it a Satnav object:

class Car():
    def __init__(self, brand, satnav=None):
        self.brand = brand
        self.satnav = satnav

class Satnav():
    def __init__(self, brand=None):
       self.brand = brand

my_car = Car('ford')
my_car.satnav = Satnav('tomtom')
  • Related