0

How should I access the class instance variables in my roll method?

Should I access self._value with self._value or use my setter by accessing with self.value? Same question for self._sides.

import random


class MSDie:
    def __init__(self, sides):
        self._sides = sides
        self._value = 1

    @property
    def sides(self):
        return self._sides

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, number):
        self._value = number

    def roll(self):
        self._value = random.randrange(1, self.sides + 1)

So basically, should I create the roll method like this instead:

def roll(self):
    self.value = random.randrange(1, self.sides + 1)

Now I know how to do it correctly the conventional way of get_value/set_value but I am trying to learn how to create more pythonic classes.

Just out of curiosity, why doesn't self.value(random.randrange(1, self.value + 1) or self.value(self, random.randrange(1, self.sides + 1) access the self._value variable and change it?

1 Answer 1

4

In your current implementation, the value-property is of no use. If you have a setter with, for example, additional checks, you have to decide, if roll needs the additional checks or not. If not sure, use self.value.

Sign up to request clarification or add additional context in comments.

1 Comment

In what case WOULD be my value-property of use? I am just learning about these decorators.

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.