2

I tried writing a custom getter for a class attribute. But I am unable of finding the right syntax in Python. I tried what is mentioned in this question but using the @property decorator does not seem to work or I am calling it incorrectly.

Class:

class Comment:
  def __init__(self):
    self.productRecommender = None

  @property
  def productRecommender(self):
    return self.productRecommender if self.productRecommender is not None else 'Onbekend'

Setting the attribute in the code (uses Selenium, comment is an instance of Comment()), should stay None if class is not found:

try:
  comment.recommender = comment.find_element_by_class_name('recommend').text
except NoSuchElementException:
  pass

Trying to access the value

comment.productRecommender
SomeDutchGuy
  • 2,249
  • 4
  • 16
  • 42
  • 1
    As in the linked question, all references to the actual underlying attribute should be prefixed: `self._productRecommender` – Tomerikoo Jan 26 '21 at 11:29
  • @Tomerikoo sorry for the indentation. Going to fix that (it's a copy/paste thing). Do you mean comment.productRecommender comment.self.productRecommender? – SomeDutchGuy Jan 26 '21 at 11:32
  • 3
    You cannot have the name of the property the same as the instance attribute name. Change you instance attribute name to `_productRecommmender`, as mentioned by @Tomerikoo – Icebreaker454 Jan 26 '21 at 11:38
  • I meant inside the class itself. Wherever you have `self.productRecommender` it should be `self._productRecommender` – Tomerikoo Jan 26 '21 at 11:52
  • @Tomerikoo, thanks. I finally got the issue looking at all the comments here and the posted example code. Need to get more used to OO in Python. – SomeDutchGuy Jan 26 '21 at 11:59

1 Answers1

1

it should be self._productRecommender and not self.productRecommender

class Comment():
    def __init__(self):
        self._productRecommender = None

    @property
    def productRecommender(self):
        print("getter called")
        return self._productRecommender if self._productRecommender is not None else 'Onbekend'

c = Comment()
foo = c.productRecommender
Josh
  • 159
  • 9