GitHub

@@ -568,96 +568,5 @@ If you want to modify the local `x` and the global `x` separately, you can creat

568568569569

We will leave this for you to explore.

570570571-

## Summary

572571573-

Messages in this lecture are clear:

574-575-

* In Python, *everything in memory is treated as an object*.

576-

* Zero, one or many names can be bound to a given object.

577-

* Every name resides within a scope defined by its namespace.

578-579-

This includes not just lists, strings, etc., but also less obvious things, such as

580-581-

* functions (once they have been read into memory)

582-

* modules (ditto)

583-

* files opened for reading or writing

584-

* integers, etc.

585-586-

Consider, for example, functions.

587-588-

When Python reads a function definition, it creates a **function object** and stores it in memory.

589-590-

The following code illustrates further this idea

591-592-

```{code-cell} python3

593-

#reset the current namespace

594-

%reset

595-

```

596-597-

```{code-cell} python3

598-

def f(x): return x**2

599-

f

600-

```

601-602-

```{code-cell} python3

603-

type(f)

604-

```

605-606-

```{code-cell} python3

607-

id(f)

608-

```

609-610-

```{code-cell} python3

611-

f.__name__

612-

```

613-614-

We can see that `f` has type, identity, attributes and so on---just like any other object.

615-616-

It also has methods.

617-618-

One example is the `__call__` method, which just evaluates the function

619-620-

```{code-cell} python3

621-

f.__call__(3)

622-

```

623-624-

Another is the `__dir__` method, which returns a list of attributes.

625-626-

We can also find `f` our current namespace

627-628-

```{code-cell} python3

629-

'f' in dir()

630-

```

631-632-

Modules loaded into memory are also treated as objects

633-634-

```{code-cell} python3

635-

import math

636-637-

id(math)

638-

```

639-640-

We can find `math` in our global namespace after the import

641-642-

```{code-cell} python3

643-

print(dir()[-1::-1])

644-

```

645-646-

We can also find all objects associated with the `math` module in the private namespace of `math`

647-648-

```{code-cell} python3

649-

print(dir(math))

650-

```

651-652-

We can also directly import objects to our current namespace using `from ... import ...`

653-654-

```{code-cell} python3

655-

from math import log, pi, sqrt

656-657-

print(dir()[-1::-1])

658-

```

659-660-

We can find these names appear in the current namespace now.

661-662-

*This uniform treatment of data in Python (everything is an object) helps keep the language simple and consistent.*

663572

Read the original on github.com ↗