newbee: object's attributes

Alexander Eisenhuth stacom at stacom-software.de
Tue Aug 13 03:13:31 EDT 2002


Thanks a lot, now i got it:

class CTest:
      ''' evaluate OOP attributes
      '''
      def __init__ (self):
          # if _l2 is not init here, we have it as "class attribute"
          self._l2 = ['obj specific']
          pass

      def objAccess(self):
          # access the obj specific attribute
          self._l2.append(1)
          print 'objAccess:%s' % self._l2

      def classAccess(self):
          print 'classAccess: %s' % CTest._l2

      _l2 = ['class specific']

obj = CTest()
obj.objAccess()
obj.classAccess()

Duncan Booth wrote:
 > Alexander Eisenhuth <stacom at stacom-software.de> wrote in
 > news:3D57D4F8.7090003 at stacom-software.de:
 >
 >
 >>class CTest:
 >>       ''' filter different link typs, identified by starting sequence
 >>       '''
 >>       def __init__ (self):
 >>           pass
 >>
 >>       def access(self):
 >>           self._l2.append(1)
 >>
 >>       _l2 = []
 >>
 >>obj = CTest()
 >>obj.access()
 >>obj.access()
 >>
 >>newObj = CTest()
 >>obj.access()
 >>
 >>
 >>must I set self._l2 in the constructor to [] that i can speak of a
 >>object specific attribute ? Is in other words _l2 a attribute of the
 >>namespace CTest ?
 >
 >
 > _l2 in your code is an attribute of the class.
 >
 > When the class statement is executed, all of the statements in the class
 > body are executed in a new namespace (much like a function call). All of
 > the local variables created while executing the class body are then used to
 > create the class attributes. In your example, the 'local' variables in the
 > class body are __init__, access and _l2, so these are stored in the class.
 >
 > Instance attributes are created when they are assigned through an instance
 > such as self. Typically you would do this first in the __init__ method, but
 > you may also create instance attributes at any other time.
 >
 > When you access a method or attribute through an instance, the instance
 > attributes are searched first, then the attributes for the class, then the
 > attributes for each base class in turn.
 >
 > New style classes (i.e. subclasses of object) search the base classes in a
 > slightly different order from old style classes and may also restrict your
 > ability to create new instance attributes.
 >





More information about the Python-list mailing list