0

I'm trying to figure out how len() is works when used inside Python class. Running this code results in the error shown, even though I added a __len__ overload and used @property, following various advice from the Internet.

class Routes:
   def __init__(self):
      self._route_list = list()

   def __len__(self):
      return len(self._route_list)

   @property
   def route_list(self):
      return self._route_list

   @classmethod
   def check_list(self):
      if not self.route_list or len(self.route_list) == 0:
         print('ERROR: no items to print!')

routes = Routes()
routes.check_list()
TypeError: object of type 'property' has no len()
martineau
  • 119,623
  • 25
  • 170
  • 301
  • The "problem" is the ``@classmethod`` decorator - remove it and your code will work. Why did you make the method a class method in the first place? Only the class instance can access ``_route_list`` – Mike Scotty Nov 15 '19 at 22:28
  • Also, looks like in your if clause `not self.route_list` and `len(self.route_list) == 0` are checking the same thing. – ndrplz Nov 15 '19 at 22:35
  • @MikeScotty I though `@classmethod` and `@staticmethod` are like non-static and static methods in C. It seems like theses two decorators are both variations of static method, and their absence means that the method is non-static. – ASPushkin80lvl Nov 15 '19 at 22:37

1 Answers1

0
class Routes:
   def __init__(self):
      self._route_list = list()

   def __len__(self):
      return len(self._route_list)

   def add_route(self):
    self._route_list.append("route")

routes = Routes()
print(len(routes)) # 0
routes.add_route()
print(len(routes)) # 1

When you override len, you are overriding the call to len with that object as the parameter. Same thing when you overload any other of those types of methods.

Andrew Grass
  • 242
  • 1
  • 8