|
Re: Python 3000 Status Update (Long!)
|
Posted: Jul 31, 2007 5:57 PM
|
|
> > Any chance we could get rid of mandatory self in > > classes, as long as everything is up for grabs? > > In just about every language I've seen that doesn't use > such a scoping identifier, you'll find ad-hoc coding > standards for marking class instance variables. For > example prefix with "m_" or postfix with "_" in C++ is > common.
Yes, and as someone pointed out, you don't _have_ to call it 'self'. You could call it 's':
def someMethod(s, other, args, here): s.other = other s.args = args s.here = here
And with that, it's no more typing than the 'm_' convention seen frequently in C++ code.
That said, I still kind of like to use 'self' most of the time because it's easy to spot. And not too onerous in most cases. There are times, however, when I want to do repeated operations to a particular member of 'self'. And for that it would be really nice if there were a way to 'import' from self (or any other object) the way you can import from a namespace.
For example, instead of:
def voom(self, jolt): self._number_of_volts += jolt if not_safe_voltage(self._number_of_volts): self._number_of_volts = min(self._safe_voltage,self._number_of_volts)
You could do:
def voom(self, jolt): from self import _number_of_volts as v v += jolt if not_safe_voltage(v): v = min(self._safe_voltage,v)
The example is somewhat contrived, but you get the idea. Sometimes you end up repeating self._some_long_member_name many times. With current Python the workaround is to use a temp and assign it back:
v = self._number_of_volts ... use v ... self._number_of_volts = v
But it's easy to forget to set it back to the original value, and often you've got several such members you want to manipulate so you end up with:
v = self._number_of_volts a = self._number_of_amps p = self._current_parrot k = self._current_shop_keeper ... use v ... self._number_of_volts = v self._number_of_amps = a self._current_parrot = p self._current_shop_keeper = k
which just seems like a big unnecessary violation of DoNotRepeatYourself.
|
|