0

I'm learning about properties, and wrote this code just to see how it works:

class Car:
    def __init__(self):
        self.cities = 0
        self.time = 0
        self.efficiency = None
    @property
    def efficiency(self):
        print('Calculating efficiency')
        self.efficiency = self.cities / self.time
        return self.efficiency
    @efficiency.setter
    def efficiency(self,input):
        self.efficiency = input

When I tried to create an objet called ejemplo (example), I get RecursionError: maximum recursion depth exceeded while calling a Python object error. Anyone knows why?

This is how I created the ejemplo:

ejemplo = Car()
print(ejemplo.cities)
print(ejemplo.time)
ejemplo.efficiency = 2

Thanks!

idmdvan
  • 29
  • 4
  • 1
    Because your `property` has the same name as your managed attribute. Typically, you would just call your managed attribute `_efficiency` in this case – juanpa.arrivillaga Aug 15 '17 at 22:30
  • `self.efficiency = ...` calls the setter, because it's defined as a property. – Ignacio Vazquez-Abrams Aug 15 '17 at 22:30
  • So, in other words, in your `__init__` when you do `self.efficiency = None`, it calls your `property.setter`, which has `self.efficiency = input`, which calls the `property.setter`... and so on and so forth... – juanpa.arrivillaga Aug 15 '17 at 22:33

0 Answers0