|
Original |
Translation |
|
21
|
One of the consequences of this is that it is error-prone to compare the result of some computation to a float with ``==``. Tiny inaccuracies may mean that ``==`` fails. Instead, you have to check that the difference between the two numbers is less than a certain threshold::
|
|
|
22
|
epsilon = 0.0000000000001 # Tiny allowed error expected_result = 0.4 if expected_result-epsilon <= computation() <= expected_result+epsilon: ...
|
|
|
23
|
Please see the chapter on :ref:`floating point arithmetic <tut-fp-issues>` in the Python tutorial for more information.
|
|
|
24
|
Why are Python strings immutable?
|
|
|
25
|
|
26
|
One is performance: knowing that a string is immutable means we can allocate space for it at creation time, and the storage requirements are fixed and unchanging. This is also one of the reasons for the distinction between tuples and lists.
|
|
|
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.
|
|