Advertisement

07.04.2008 at 06:44PM PDT, ID: 23540221
[x]
Attachment Details

Python class variables don't actually appear to be static variables.

Asked by HappyEngineer in Python Scripting Language

Tags: python

Python has class and data variables. As a java programmer I started out thinking that class variables are static variables and data variables are instance variables. However, that does not appear to be quite right.

Here is my example:


class Shape:
    def sides(self):
        return self.numSides;
class Pentagon(Shape):    
    numSides = 5
    def __init__(self):
        pass
class Square(Shape):    
    numSides = 4
    def __init__(self):
        pass

if __name__ == "__main__":
    pentagon = Pentagon()
    square1 = Square()
    square2 = Square()
    square2.__class__.numSides = 42
   
    print pentagon.sides()
    print square1.sides()
    print square2.sides()

    square3 = Square();
    square2.numSides = 7
   
    print pentagon.sides()
    print square1.sides()
    print square2.sides()
    print square3.sides()


That code prints out
5
42
42
5
42
7
42

That confuses me. The numSides variable is clearly an instance variable, otherwise square2.numSides = 7 would set the numSides value for square1, square2, and square3. But, it is also clearly a static variable when referred to using square2.__class__.numSides = 42 because using that does set the variable in all instances of Square.

So is the real answer that numSides is always an instance variable, but __class__ can be used to find all instances of the class and set those variables to a value as well as change the default value for new instances of that class?

That's what it looks like to me, but the description in the Dive Into Python book does not mention anything about that behavior:
    http://www.diveintopython.org/object_oriented_framework/class_attributes.html

Start Free Trial
[+][-]07.05.2008 at 01:26AM PDT, ID: 21936323

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 7-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]07.05.2008 at 01:53PM PDT, ID: 21938354

View this solution now by starting your 7-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

 

About this solution

Zone: Python Scripting Language
Tags: python
Sign Up Now!
Solution Provided By: pepr
Participating Experts: 2
Solution Grade: A
 
 
 
Loading Advertisement...
20080716-EE-VQP-32 / EE_QW_EXPERT_20070906