|
Original |
Translation |
|
27
|
Another advantage is that strings in Python are considered as "elemental" as numbers. No amount of activity will change the value 8 to anything else, and in Python, no amount of activity will change the string "eight" to anything else.
|
|
|
28
|
Why must 'self' be used explicitly in method definitions and calls?
|
|
|
29
|
The idea was borrowed from Modula-3. It turns out to be very useful, for a variety of reasons.
|
|
|
30
|
First, it's more obvious that you are using a method or instance attribute instead of a local variable. Reading ``self.x`` or ``self.meth()`` makes it absolutely clear that an instance variable or method is used even if you don't know the class definition by heart. In C++, you can sort of tell by the lack of a local variable declaration (assuming globals are rare or easily recognizable) -- but in Python, there are no local variable declarations, so you'd have to look up the class definition to be sure. Some C++ and Java coding standards call for instance attributes to have an ``m_`` prefix, so this explicitness is still useful in those languages, too.
|
|
|
31
|
|
32
|
Finally, for instance variables it solves a syntactic problem with assignment: since local variables in Python are (by definition!) those variables to which a value is assigned in a function body (and that aren't explicitly declared global), there has to be some way to tell the interpreter that an assignment was meant to assign to an instance variable instead of to a local variable, and it should preferably be syntactic (for efficiency reasons). C++ does this through declarations, but Python doesn't have declarations and it would be a pity having to introduce them just for this purpose. Using the explicit ``self.var`` solves this nicely. Similarly, for using instance variables, having to write ``self.var`` means that references to unqualified names inside a method don't have to search the instance's directories. To put it another way, local variables and instance variables live in two different namespaces, and you need to tell Python which namespace to use.
|
|
|
33
|
Why can't I use an assignment in an expression?
|
|
|
34
|
Many people used to C or Perl complain that they want to use this C idiom:
|
|
|
35
|
while (line = readline(f)) { // do something with line }
|
|
|
36
|
where in Python you're forced to write this::
|
|