0

I have below Car class. I would like to be able to reset the mileage for all car class instances to 0. How can I do this?

class Car():

        carpark = []

        # initialising instance

        def __init__(self, brand, color, fuel, mileage):
            self.brand = brand
            self.color = color
            self.fuel = fuel
            self.mileage = mileage
            self.drives = []

            Car.carpark.append(self)

        @classmethod
        def purchase(cls, brand, color):
            cls(brand, color, "Diesel", 0)

Since I have the carpark list, i could do something like:

@classmethod
def reset_mileage(cls):
for car in cls.carpark:
    car.mileage = 0 

This works but I am wondering if there is a better, cleaner way to do this?

2
  • You could create a reset_mileage function in the Car class which sets its mileage to 0. And then call that for each car in the collection. It's usually not a good idea for a class instance to control/modify the collection it is a part of. Commented Aug 24, 2018 at 17:38
  • What you have for mileage resetting seems fine to me. Generally, for questions regarding the style of working code, you might consider asking them at Code Review. Commented Aug 24, 2018 at 17:45

1 Answer 1

1

It is possible to use Python's property feature to update the attributes lazily - just keep a tick counter on the class, and the corresponding tick on each instance:

class Car:
   cls_mileage = 0 
   cls_mileage_tick = 0

   @classmethod
   def reset_mileage(cls, value=0):
       cls.cls_mileage = value
       cls.cls_mileage_tick = value


   def __init__(self):
       self.mileage_tick = self.cls_mileage_tick
       self.mileage = 0

   @property 
   def mileage(self):
       if self._mileage_tick < self.cls_mileage_tick:
           self._mileage_tick = self.cls_mileage_tick
           self._mileage = self.cls_mileage
       return self._mileage

   @mileage.setter
   def mileage(self, value):
       self._mileage_tick = self.cls_mileage_tick
       self._mileage = value

Here is some explanation on the @property decorator. This is some sort of "reactive pattern" on top of that. - https://www.programiz.com/python-programming/property

Of course, if you need this for a lot of attributes, this pattern requires a lot of code for each one, there are ways to make this generic using the __getattribute__ and __setattr__ magic methods.

Also, if you can be sure of whether you are getting and setting an attribute on the instance or the class itself , there is no need for the extra cls_ prefix on both class attributes: the names can be re-used.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.