[Tutor] R: Re: Re: Re: Class learning
steve at pearwood.info
Sun Jan 25 09:00:22 CET 2015
Sorry folks, I haven't been keeping up with this specific thread, so I'm
going to just jump in with an opinion no matter how ignorant... :-)
On Sun, Jan 25, 2015 at 07:20:18AM +1100, Cameron Simpson wrote:
> Like Alan, you've missed my intent here.
> To quote from my reply to Alan:
> I am not referring to the overhead of making a function call, but the
> intuitive cost that distinguishes something one thinks of as an attribute
> something one thinks of as a function: a function may entain an arbitrary
> amount of work whereas an attibute is almost free, and constant in cost.
> I'm not talking about optimisation here, I'm talking about the notion of a
> value that is derived from (unspecified and perhaps costly) computation
> a value that is merely stored, and trivially retrieved.
If I understand you correctly, I think what you are trying to get across
is that if you have a computed value which is *conceptually* just a
attribute look-up, use a property, but if it is conceptually a matter of
detailed calculation (or if, in fact, it actually is an expensive
calculation) then make it a method call. Something like this:
# not necessarily four, some dogs have lost limbs and
# there are mutant dogs with more than four legs
legs = [part for part in self.body_parts
if isinstance(part, Leg)]
"""Count the number of fleas on the dog."""
count = 0
area = get_surface(self)
grid = divide_into_grid(area)
for section in grid:
n = Inspect(section).count(Flea)
count += n
The number of legs feels like a simple attribute of the dog, which we
should be able to take in at a glance. Counting the number of fleas on
a dog feels like something hard and time consuming. In this case, our
intuition about what is hard and what is easy is probably correct, but
it may not be for all classes.
If you have a computed attribute, and it feels like it should be cheap
to calculate, and it actually is cheap to calculate, then make it a
property. If it is expensive, then make it a method.
More information about the Tutor