Class Variable Access and Assignment

Magnus Lycka lycka at carmen.se
Mon Nov 7 06:05:40 EST 2005


First of all, I've still not heard any sensible suggestions
about a saner behaviour for augmented assignment or for the
way Python searches the class scope after the instance scope.

What do you suggest?

Today, x += n acts just as x = x + n if x is immutable.
Do you suggest that this should change?

Today, instance.var will look for var in the class
scope if it didn't find it in the instance scope. Do
you propose to change this?

Or, do you propose that we should have some second order
effect that makes the combination of instance.var += n
work in such a way that these features are no longer
orthogonal?

Paul Rubin wrote:
> Steven D'Aprano <steve at REMOVETHIScyber.com.au> writes:
> 
>>A basic usage case:
>>
>>class Paper:
>>    size = A4
>>    def __init__(self, contents):
>>        # it makes no sense to have class contents,
>>        # so contents go straight into the instance
>>        self.contents = contents
> 
> 
> So add:
> 
>          self.size = Paper.size
> 
> and you've removed the weirdness.  What do you gain here by inheriting?

class LetterPaper(Paper):
     size = Letter

class LegalPaper(Paper):
     size = Legal

This is what you gain. Subclassing it extremely simple, if all
you want is that the subclass differs in data. You could also
have __init__ pick up the class variable and set an instance
variable, but why make things difficult if it's trivial now?

Considering how __init__ works in Python class hierachies,
where you need to manually call __init__ in ancestor classes
if you've overridden them, the fact that a simple self.size
picks up a class variable is particularly useful if you use
MI. For instance I could imagine a FirstPageMixin class in
this case, and a FancyFirstPageMixin that subclasses that.
There, we might want to pick up certain margin values or
other positions etc.

The spirit of Python is to make it easy to do things right,
not make it difficult to make mistakes. If you want a language
that tries to prevent you from making mistakes, use Ada.

When developing code in a dynamic language such as Python,
it's really important to have a decent set of automated tests.
If you have, you'll hopefully notice bugs like these. Making
changes in the language that forces you to write more code
will in general not reduce the total number of bugs, but
rather increase them.

I've been involved with high reliability design long enough to
know the problems involved fairly well. I mainly worked with
electronic design then, but the problem is the same: The more
safety gadgets you add, the more stuff you have that can break.
The details are a bit difference, but in principle the problem
is the same.

Ever wondered why Russian and Chinese rocket launchers have a
better reliability than the American? Simply put, they're simpler.



More information about the Python-list mailing list