Using eval, or something like it...

Scott David Daniels Scott.Daniels at Acm.Org
Fri Nov 21 02:25:37 CET 2008


r0g wrote:
> ...
> A class is like a template which combines a complex data type (made from
> a combination of other data types) and the methods that operate on that
> data type.
> 
> You generally don't work with classes directly but you make instances of
> them, each instance has it's own internal state and methods, initially
> these are the same as the templates but can be changed or overridden
> without affecting the state of any other instances you might have.
Take the tutorial and do experiments.
The attribute lookup checks the class _and_ the instance (with the
instance over-riding the class).  Make sure you can explain the output
from this:

     class Demo(object):
         non_template = 43

     d = Demo()
     print d.non_template
     Demo.non_template = 44
     print d.non_template
     d.non_template = 45
     print d.non_template
     Demo.non_template = 46
     print d.non_template

Once you can do that, explain this:
     class Demo2(object):
         holder = []

     e = Demo2()
     print e.holder
     Demo2.holder.append(44)
     print e.holder
     e.holder.append(45)
     print e.holder
     Demo2.holder.append(46)
     print e.holder

     # clue:
     print d.holder is Demo.holder

> Is this correct enough for me to avoid the aforementioned bug pile?
> 
> Also then, what _is_ an "instance variable" ?

Well, when you use the term variable, I suspect that you think it
represents storage.  OK, it kind of does, but only in the sense
that it can hold a reference to an object.  A more successful
way of thinking is that the attribute name is associated with the
value.  In fact the object typically has a dictionary doing exactly
that, associating attribute names with values.  Both the class and
the instance have such dictionaries, although there are a few "specials"
that don't work that way (setattr knows about checking for the 
exceptional cases).  The "storage" can be removed with the "del"
statement.  Try
     del d.non_template
     print d.non_template
     del e.holder
     print e.holder

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list