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
5
  • 1
    As in the linked question, all references to the actual underlying attribute should be prefixed: self._productRecommender Commented Jan 26, 2021 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? Commented Jan 26, 2021 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 Commented Jan 26, 2021 at 11:38
  • I meant inside the class itself. Wherever you have self.productRecommender it should be self._productRecommender Commented Jan 26, 2021 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. Commented Jan 26, 2021 at 11:59

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Some explanations make an answer much more valuable than code-only...

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.