Python property vs method when no access to attribute is needed?

Viewed 12669

I am reading "Python programming for the absolute beginner" and in there there is this piece of code:

@property
def mood(self):
    unhappiness = self.hunger + self.boredom
    if unhappiness < 5:
        m = "happy"
    elif 5 <= unhappiness <= 10:
        m = "okay"
    elif 11 <= unhappiness <= 15:
        m = "frustrated"
    else:
        m = "mad"
    return m

All it does is calculate on-the-fly and return the calculation. It doesn't provide access to a private attribute or any attribute of the class. Is this better as property rather than method?

5 Answers

There is actually a very good reason to use this (which I just encountered). In your case, it may not seem like doing much. But imagine having two classes:

class Person(object):
    hunger = 3
    boredom = 5

    @property
    def mood(self):
        unhappiness = self.hunger + self.boredom
        if unhappiness < 5:
            m = "happy"
        elif 5 <= unhappiness <= 10:
            m = "okay"
        elif 11 <= unhappiness <= 15:
            m = "frustrated"
        else:
           m = "mad"
        return m

class Werewolf(object):
    mood = "mad"

In this case, "Werewolf's" are always "mad", but "Person's" are conditionally "mad".

Now, if you had a generic method where:

if time == "full moon"
    player = Werewolf
else:
    player = Person

then you can "safely" just say

mood_at_this_time = player.mood

without worrying about making a method call.

Related