Why does Python seem to treat instance variables as shared between objects?

前端 未结 3 681
旧巷少年郎
旧巷少年郎 2020-12-17 02:12

I was working on a simple script today when I noticed a strange quirk in the way Python treats instance variables.

Say we have a simple object:

class         


        
3条回答
  •  天涯浪人
    2020-12-17 03:02

    As Ignacio has posted, variables which are assigned to at class scope in Python are class variables. Basically, in Python, a class is just a list of statements under a class statement. Once that list of statements finishes executing, Python scoops up any variables that were created during the course of that execution and makes a class out of them. If you want an instance variable, you actually do have to assign it to the instance.

    On another note: it sounds like you may be coming to this from a Java (or Java-like) perspective. So perhaps you know that because Java requires variables to be explicitly declared, it needs to have instance variable declarations at class scope.

    class Foo {
        String bar;
        public Foo() {
            this.bar = "xyz";
        }
    }
    

    Note that only the declaration is at class scope. In other words, the memory allocated for that variable is part of the class "template," but the actual value of the variable is not.

    Python doesn't have any need for variable declarations. So in the Python translation, you just drop the declaration.

    class Foo:
        # String bar;  <-- useless declaration is useless
        def __init__(self):
            self.bar = "xyz"
    

    The memory will be allocated when it's needed; only the assignment is actually written out. And that goes in the constructor, just like in Java.

提交回复
热议问题