[Tutor] R: Re: Re: Re: Class learning

Danny Yoo dyoo at hashcollision.org
Sat Jan 24 02:16:50 CET 2015


>
> But why a property rather than a simple method?
> Why is
>
> k = url.key
>
> better than
>
> k = url.key()
>
> for meeting those criteria?


My understanding is this is very much a Python-specific problem.
Python style encourages raw access to the attributes of an object via
direct lookup and assignment.  We use underscores conventionally to
hide private details.

The language itself says very little about privacy enforcement.  Given
that state of the world, people wrote code.  And once something's
written, it has a legacy.  Once we have legacy code full of attribute
setting and getting, we might revise our view and desire to manage
those attributes more carefully.  Maybe we want to compute those
values lazily and cache aggressively.  Maybe we want to make sure an
attribute's value is always a positive integer.

In other languages like Java, we can do this management with explicit
setters and getters: we can have code that does runtime checks before
permitting an attribute to be assigned.  That's one reason for the
getter/setter boilerplate we see out there: it's all in preparation
for the inevitable code revision.

But maybe we don't want to rewrite all that legacy code.  Python
properties let us retrofit setter/getter-like attribute management,
but without having to rewrite clients to use method calls.  It's
syntactic sugar.

---

In the context of beginner programming, there's no "legacy code" to
talk about, so that's why I don't think it's appropriate to teach
properties to beginners: it's not the right audience.


More information about the Tutor mailing list