Peng said:
I am more familiar with C++ than python. So I need to connect python
concept to C++ concept so that I can understand it better.
name1 and name are all references (in the C++ sense), right?
__repr__ and __str__ are references (in the C++ sense) to functions
and both of them could refer to the same function or two different
ones, right?
Regards,
Peng
By limiting yourself to C++ terminology, you're restricting how well you
can understand it. But I'll try.
C++ references cannot change. And C++ functions cannot be created on
the fly. But otherwise, these names work kinda like C++ references.
Perhaps it'd help if I try to describe how some of this stuff works.
For now, let's skip classes entirely, and just deal with top-level stuff
(global scope).
Let's say we're in a module called mymodule.py. So there's an object
called mymodule, with a dictionary in it containing some attributes
This dictionary works just like any dictionary you might define, but
it's "under the covers," so to speak. You add stuff to this dictionary
by doing an "assignment."
name1= "value"
creates a new string object, and adds a dictionary item with key of
"name1" and value of pointer-to-the-string-object
name2 = 42
does the same thing, but it's an int object.
name1 = name2 doesn't create a new dictionary item, since it's already
there. But it changes the value of the item from ptr-to-int to
ptr-to-string. At this point, the string object doesn't have any refs,
so it probably gets freed. And the int object has two refs. It doesn't
know what they are, just that the count is two.
def myfunct():
return 12
creates a code object, and adds a dictionary item with key of "myfunct"
and value of pointer-to-the-code-object.
otherfunct = myfunct creates a new dictionary item with the same value
as the existing one. And ref count goes to two.
Notice that there's nothing stopping you from doing
name1 = myfunct
and now name1 acts like a function, instead of a string or an int. All
these things are first-class objects.
One more piece for today's lesson:
import othermodule
This creates an entry in our module dictionary with key of "othermodule"
and value pointing to the imported module.
Now, we can get at our own symbols by name1, or name2. And we can get
at symbols from othermodule by othermodule.name3
This simply finds othermodule in the current global dictionary, then
looks up name3 in that othermodule's dictionary.
Clearer ?