On the property function

Lie Ryan lie.1296 at gmail.com
Tue Jun 16 06:14:13 EDT 2009


Chris Rebert wrote:
> On Mon, Jun 15, 2009 at 5:43 AM, Virgil Stokes<vs at it.uu.se> wrote:
>> Does anyone have a good example (or examples) of when "property(...)" can be
>> useful?
> 
> Erm, when you want to create a property (i.e. computed attribute).
> 
> from __future__ import division
> class TimeDelta(object):
>     def __init__(self, secs):
>         self. seconds =secs
> 
>     @property
>     def minutes(self):
>         return self.seconds/60
> 
>     @property
>     def hours(self):
>         return self.minutes/60
> 
>     @property
>     def days(self):
>         return self.hours/24
> 
> td = TimeDelta(55555555555)
> print td.days, "days", "=", td.hours, "hours", "=", td.minutes, "minutes"
> 
> Cheers,
> Chris


Python's property is better than just that...

from __future__ import division
class TimeDelta(object):
    def __init__(self, secs):
        self. seconds =secs

    @property
    def minutes(self):
        return self.seconds
    @minutes.setter
    def minutes(self, value
        self.seconds = 60 * value

    @property
    def hours(self):
        return self.minutes/60
    @hours.setter
    def hours(self, value):
        self.minutes = 60 * value

    @property
    def days(self):
        return self.hours/24
    @days.setter
    def days(self, value):
        self.hours = 24 * value



More information about the Python-list mailing list