Teks sumber — English
Terjemahan — Bahasa Indonesia
It works by scanning your source recursively for import statements (in both forms) and looking for the modules in the standard Python path as well as in the source directory (for built-in modules). It then turns the bytecode for modules written in Python into C code (array initializers that can be turned into code objects using the marshal module) and creates a custom-made config file that only contains those built-in modules which are actually used in the program. It then compiles the generated C code and links it with the rest of the Python interpreter to form a self-contained binary which acts exactly like your script.
Why are default values shared between objects?
It is often expected that a function call creates new objects for default values. This is not what happens. Default values are created exactly once, when the function is defined. If that object is changed, like the dictionary in this example, subsequent calls to the function will refer to this changed object.
By definition, immutable objects such as numbers, strings, tuples, and ``None``, are safe from change. Changes to mutable objects such as dictionaries, lists, and class instances can lead to confusion.
Because of this feature, it is good programming practice to not use mutable objects as default values. Instead, use ``None`` as the default value and inside the function, check if the parameter is ``None`` and create a new list/dictionary/whatever if it is. For example, don't write::
Variables are simply names that refer to objects. Doing ``y = x`` doesn't create a copy of the list -- it creates a new variable ``y`` that refers to the same object ``x`` refers to. This means that there is only one object (the list), and both ``x`` and ``y`` refer to it.
we can see that in this case ``x`` and ``y`` are not equal anymore. This is because integers are :term:`immutable`, and when we do ``x = x + 1`` we are not mutating the int ``5`` by incrementing its value; instead, we are creating a new object (the int ``6``) and assigning it to ``x`` (that is, changing which object ``x`` refers to). After this assignment we have two objects (the ints ``6`` and ``5``) and two variables that refer to them (``x`` now refers to ``6`` but ``y`` still refers to ``5``).
However, there is one class of operations where the same operation sometimes has different behaviors with different types: the augmented assignment operators. For example, ``+=`` mutates lists but not tuples or ints (``a_list += [1, 2, 3]`` is equivalent to ``a_list.extend([1, 2, 3])`` and mutates ``a_list``, whereas ``some_tuple += (1, 2, 3)`` and ``some_int += 1`` create new objects).
Remember that arguments are passed by assignment in Python. Since assignment just creates references to objects, there's no alias between an argument name in the caller and callee, and consequently no call-by-reference. You can achieve the desired effect in a number of ways.
>>> def func1(a, b):
... a = 'new-value' # a and b are local names
... b = b + 1 # assigned to new objects
... return a, b # return new values
...
>>> x, y = 'old-value', 99
>>> func1(x, y)
('new-value', 100)
You have two choices: you can use nested scopes or you can use callable objects. For example, suppose you wanted to define ``linear(a,b)`` which returns a function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes::
In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case. Not all objects can be copied, but most can.
Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy` method::
Generally speaking, it can't, because objects don't really have names. Essentially, assignment always binds a name to a value; the same is true of ``def`` and ``class`` statements, but in that case the value is a callable. Consider the following code::
For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the :meth:`~str.split` method of string objects and then convert decimal strings to numeric values using :func:`int` or :func:`float`. :meth:`!split` supports an optional "sep" parameter which is useful if the line uses something other than whitespace as a separator.
:class:`str` and :class:`bytes` objects are immutable, therefore concatenating many strings together is inefficient as each concatenation creates a new object. In the general case, the total runtime cost is quadratic in the total string length. See :ref:`time-complexity` for more information.
To accumulate many :class:`str` objects, the recommended idiom is to place them into a list and call :meth:`str.join` at the end::
To accumulate many :class:`bytes` objects, the recommended idiom is to extend a :class:`bytearray` object using in-place concatenation (the ``+=`` operator)::
result = bytearray()
for b in my_bytes_objects:
result += b
Lists are equivalent to C or Pascal arrays in their time complexity; the primary difference is that a Python list can contain objects of many different types.
The reason is that replicating a list with ``*`` doesn't create copies, it only creates references to the existing objects. The ``*3`` creates a list containing 3 references to the same list of length two. Changes to one row will show in all rows, which is almost certainly not what you want.
How do I apply a method or function to a sequence of objects?
This is because of a combination of the fact that augmented assignment operators are *assignment* operators, and the difference between mutable and immutable objects in Python.
This discussion applies in general when augmented assignment operators are applied to elements of a tuple that point to mutable objects, but we'll use a ``list`` and ``+=`` as our exemplar.
Objects
Objek
A class is the particular object type created by executing a class statement. Class objects are used as templates to create instance objects, which embody both the data (attributes) and code (methods) specific to a datatype.
If your data structures contain circular links (for example, a tree where each child has a parent reference and each parent has a list of children) the reference counts will never go back to zero. Once in a while Python runs an algorithm to detect such cycles, but the garbage collector might run some time after the last reference to your data structure vanishes, so your :meth:`!__del__` method may be called at an inconvenient and random time. This is inconvenient if you're trying to reproduce a problem. Worse, the order in which object's :meth:`!__del__` methods are executed is arbitrary. You can run :func:`gc.collect` to force a collection, but there *are* pathological cases where objects will never be collected.
Despite the cycle collector, it's still a good idea to define an explicit ``close()`` method on objects to be called whenever you're done with them. The ``close()`` method can then remove attributes that refer to subobjects. Don't call :meth:`!__del__` directly -- :meth:`!__del__` should call ``close()`` and ``close()`` should make sure that it can be called more than once for the same object.
Another way to avoid cyclical references is to use the :mod:`weakref` module, which allows you to point to objects without incrementing their reference count. Tree data structures, for instance, should use weak references for their parent and sibling references (if they need them!).
The two ids belong to different integer objects that are created before, and deleted immediately after execution of the ``id()`` call. To be sure that objects whose id you want to examine are still alive, create another reference to the object:
As recommended by :pep:`8`, an identity test is the preferred way to check for ``None``. This reads like plain English in code and avoids confusion with other objects that may have boolean values that evaluate to false.
Detecting optional arguments can be tricky when ``None`` is a valid input value. In those situations, you can create a singleton sentinel object guaranteed to be distinct from other objects. For example, here is how to implement a method that behaves like :meth:`dict.pop`:
Container implementations sometimes need to augment equality tests with identity tests. This prevents the code from being confused by objects such as ``float('NaN')`` that are not equal to themselves.
from modname import some_objects
will continue to work with the old version of the imported objects. If the module contains class definitions, existing class instances will *not* be updated to use the new class definition. This can result in the following paradoxical behaviour::
The nature of the problem is made clear if you print out the "identity" of the class objects::
Sifat masalah dibuat jelas jika Anda mencetak "identitas" objek kelas::