generating method names 'dynamically'
peter at engcorp.com
Fri Jan 27 01:30:09 CET 2006
Daniel Nogradi wrote:
> Thanks for all the replies, it became clear that I need to look into
> getattr, __getattr__ and __call__. I'll do that, but since you asked,
> here is the thing I would like to do in a little more detail:
> My database has 1 table with 2 fields, one called 'name' and the other
> one called 'age', let's suppose it has the following content, but this
> content keeps changing:
> Alice 25
> Bob 24
> ----------- program1.py ----------------
> class klass:
> # do the stuff with getattr using the database
> # but in a way that after the database changes
> # I don't need to rewrite this part
> inst = klass()
> ---------- program2.py ------------------
> import program1
> # This should print 'Hello, my name is Bob and I'm 24'
Where is the code that should print that? The code has to be defined,
and is presumably outside your database, so *that* is the method you
need to call, not something generated dynamically at runtime.
> # This should print 'Hi, I'm 25 and I'm Alice'
That actually prints something different... did you intentionally change
the order? In other words, is the code that generates that output for
Alice() actually different than the code for Bob() (and if so, where
would you define it?) or did you just write the example imprecisely?
Ultimately, I think the question here is "why do you want to do that"?
Normally you would just make Bob and Alice parameters, as in:
program1.inst.output("Alice") # prints whatever you wanted above
program1.inst.output("Bob") # prints whatever you wanted above, assuming
the differences in the two outputs was inadvertent
program1.inst.output("John") # raise exception
More information about the Python-list