Class Variables (Python 2.2/2.3)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • srijit@yahoo.com

    Class Variables (Python 2.2/2.3)

    Hello Members,
    I do not see any direct mention of class variables in new style
    classes. Only class methods. Have I missed or is it trivial? If not,
    how to define/implement class variables for new style classes?

    Regards,
    Srijit
  • Peter Otten

    #2
    Re: Class Variables (Python 2.2/2.3)

    srijit@yahoo.co m wrote:
    [color=blue]
    > Hello Members,
    > I do not see any direct mention of class variables in new style
    > classes. Only class methods. Have I missed or is it trivial? If not,
    > how to define/implement class variables for new style classes?[/color]

    From my practical point of view, there are no differences between old and
    new style classes in this respect:

    def printThem():
    for t in t1, t2, t3:
    print t.name, "=", t.color
    print

    #the same goes for class Test(object): ...
    class Test:
    color = "blue"
    def __init__(self, name):
    self.name = name

    t1 = Test("t1")
    t2 = Test("t2")
    t3 = Test("t3")

    # class atttribute are accessed like instance attributes
    printThem() #blue, blue, blue

    # class attributes are shaded by instance attributes,
    # which makes them good default values
    t1.color = "red"
    printThem() #red, blue blue

    # class attributes are not copied on instantiation
    Test.color = "green"
    printThem() #red, green, green

    And now let the experts speak up on the subtler aspects :-)

    Peter

    Comment

    • Peter Otten

      #3
      Re: Class Variables (Python 2.2/2.3)

      srijit@yahoo.co m wrote:
      [color=blue]
      > Hello Members,
      > I do not see any direct mention of class variables in new style
      > classes. Only class methods. Have I missed or is it trivial? If not,
      > how to define/implement class variables for new style classes?[/color]

      From my practical point of view, there are no differences between old and
      new style classes in this respect:

      def printThem():
      for t in t1, t2, t3:
      print t.name, "=", t.color
      print

      #the same goes for class Test(object): ...
      class Test:
      color = "blue"
      def __init__(self, name):
      self.name = name

      t1 = Test("t1")
      t2 = Test("t2")
      t3 = Test("t3")

      # class atttribute are accessed like instance attributes
      printThem() #blue, blue, blue

      # class attributes are shaded by instance attributes,
      # which makes them good default values
      t1.color = "red"
      printThem() #red, blue blue

      # class attributes are not copied on instantiation
      Test.color = "green"
      printThem() #red, green, green

      And now let the experts speak up on the subtler aspects :-)

      Peter

      Comment

      Working...