Class Variables (Python 2.2/2.3)

Discussion in 'Python' started by srijit@yahoo.com, Aug 23, 2003.

  1. Guest

    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
    , Aug 23, 2003
    #1
    1. Advertising

  2. Peter Otten Guest

    wrote:

    > 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?


    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
    Peter Otten, Aug 23, 2003
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. avnrao
    Replies:
    0
    Views:
    3,353
    avnrao
    May 7, 2004
  2. dwok
    Replies:
    7
    Views:
    689
    Hal Rosser
    Mar 4, 2005
  3. Replies:
    10
    Views:
    35,851
    jporter892
    Jun 6, 2011
  4. E11
    Replies:
    1
    Views:
    4,720
    Thomas Weidenfeller
    Oct 12, 2005
  5. Replies:
    9
    Views:
    931
Loading...

Share This Page