Search code examples
python-3.xclassooprecursionindentation

Python ignores indentation and continues to run code as part of the class in VSCode


Ok, this one might be totally stupid but here goes. I create a simple class in python using VSCode. I then create an instance of the class and it just keeps running and creating instances until I get RecursionError: maximum recursion depth exceeded, as if the unindented code was part of the class.

class Account:
   def __init__(self, initialCash):
      self.money = initialCash
      print("New account created. Initial budget: " + self.money)

   @property
   def money(self):
      return self.money

   @money.setter
   def money(self, value):
      self.money = value

account2 = Account(100)

The indentation is 3 spaces, automatic, as set in VSCode settings. What am I missing?


Solution

  • self.money calls the setter, which calls the setter, which ...

    You have to rename the attribute:

    class Account:
        def __init__(self, initial_cash):
            self._money = initial_cash
            print(f"New account created. Initial budget: {self.money}")
    
        @property
        def money(self):
            return self._money
    
        @money.setter
        def money(self, value):
            self._money = value