morfizm (morfizm) wrote,
morfizm
morfizm

  • Mood:

Python

Python has a different concept of static variables (to be precise, static class members). I had to spend a few minutes to wrap my head around it. In the following example, you'll see that static variables are being copied as references to all child objects. When they change reference to a new object, it's no longer static: not visible from instance of class type, or from other class instances. When you change only value (modify the object referenced), this is seen from everywhere, as I would expect for static objects.

So the right way to think of static variables is that you're providing a default, which will be copied into class type instance once. Hence, if it's a mutable object, it will be shared, except for class instances that replace it, and if it's immutable, it won't be shared.

Enjoy :)
class MutableValue():
    def __init__(self, value):
        self.value = value

    def __repr__(self):
        return str(self.value)

class MyClass():
    var = MutableValue(1)

def main():
    c1 = MyClass()
    c2 = MyClass()
    c3 = MyClass()
    print(MyClass.var, c1.var, c2.var, c3.var) 
    # 1, 1, 1, 1 -- all values equal
    
    c1.var = 2
    print(MyClass.var, c1.var, c2.var, c3.var) 
    # 1, 2, 1, 1 -- c1 changed to 2, other fields unaffected

    MyClass.var.value = 3
    print(MyClass.var, c1.var, c2.var, c3.var) 
    # 3, 2, 3, 3 -- ...woops! Everything is now 3 =)
    # except for c1 where we replaced the value

    c2.var.value = 4
    print(MyClass.var, c1.var, c2.var, c3.var)
    # 4, 2, 4, 4 -- and now everything is 4, except for c1

main()
(Syntax highligher used: http://tohtml.com/python/)
Tags: in english, software development
Subscribe
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 13 comments