Creating "virtual" module-namespace
Robin Munn
rmunn at pobox.com
Thu Dec 12 10:55:05 EST 2002
Harald <simon.12.ghum at spamgourmet.com> wrote:
>> It's because b is a dictionary. b['nasenbaer']() would have worked,
>> I think, but I don't think it's what you wanted.
> No, that is not wat I wanted :-=
>
>> I would do it this way. I'm assuming "something" is an object (an
>> instance of some class) and you want to be able to call
>> something.nasenbaer().
> Not att all... something can be NO object, because nasenbaer is a class
> and will instanciate it's own objects.
>From your variable names I assume German is your native language? When
you say "something can be NO object" do you mean (please excuse my
German spelling) "'something' kann kein Objekt sein"? In that case, the
proper way to say it in English would be "'something' can NOT be an
object."
But you are wrong; something COULD be an object. Python makes no
distinction between what types of things a name can point to. A name can
point to a class, a function, a list, an object, a dict... And that name
can be in any namespace -- and objects have their own namespace.
Therefore, this is perfectly legal:
class Record: pass
something = Record()
class nasenbaer:
# Insert definition here...
def __init__(self):
# Do stuff
pass
something.foo = nasenbaer
a = something.foo() # Equivalent in every way to the next line
a = nasenbaer()
What is happening here is that a name 'foo' is created in the namespace
of object 'something' -- so it is therefore accessed by 'something.foo'
since the period operator means namespace lookup. That name,
'something.foo', points to the same thing that the name nasenbaer points
to: a class definition.
Python's absolute separation between the concept of names and what they
point to is one of the biggest sources of confusion that I have seen; it
was an epiphany for me, coming to Python from places like C and Perl,
when I finally understood it. Just to make it clear: this:
def func(foo, bar):
return foo + bar
does NOT create a function called 'func'! It creates a *function object*
and also creates a name 'func' which *points to* the function object.
But there is nothing stopping you from redefining the name func:
func = some_other_function
at which point the original function object (the one that would return
the sum of its two arguments) will have no names pointing to it at all
and will be inaccessible.
I hope this helps.
--
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838
More information about the Python-list
mailing list