help on object programing

Scott David Daniels daniels at dsl-only.net
Sat Aug 18 00:55:46 EDT 2007


yadin wrote:
> class big(self):
> ...
> how can i define my variables so that there are valid outside the
> class???

Although you did not describe the issue all that well, I _think_ you
are referring to the fact that the following two pieces of code behave
less like each other than one might suspect.  The previous responders
have missed the confusing part of python in your attempt to present your
confusion.

     def big():
         abc = 7
         print abc
         class small(object):
             print '...'
             print abc
             def __init__(self):
                 print abc
         return small()
     big()

     class Big(object):
         Abc = 13
         print Abc
         class Small(object):
             print '...'
             print Abc
             def __init__(self):
                 print Abc
         cell = Small()
     big()

The explanation is unfortunately a little technical.  The
class-in-a-function (small) is not defined until the function
(big) is actually _called_, not when big is being defined.  The
class-in-a-class (Small) in the second instance is actually
defined _before_ Big is being defined, and the temporary
namespace that contains Abc is hidden while Small is being
defined.

-Scott David Daniels
Scott.Daniels at Acm.Org






More information about the Python-list mailing list