Diffs class vars vs. instance vars?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • true911m
    New Member
    • Dec 2006
    • 92

    #1

    Diffs class vars vs. instance vars?

    I'm getting ready to launch another long-winded project inquiry for feedback from you guys, cause I'm still working on the finer points of class implementation in my stubborn head.

    While I was playing around with an idea, I was reading about class vs. instance variables. I tried a few in multiple instances of a class, and I don't really get the big difference. Instance variables are definitely harder to get at -- it appears the class must have a method that is called to set/get the values within each instance from/to the outside world, but other than that, what's the big deal? Class vars are still unique to each instance, they're just reachable directly from the outside.

    Am I missing something fundamental here? Please toss out whatever comes to mind.

    Thanks.
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    This might help you get your mind around this issue:

    Code:
    class HasClassVars(object):
        # class variables
        cv1 = 4
        cv2 = 8
        def __init__(self, data):     # Constructor args often become instance variables
            self.data = data
    
        def PrintData(self):  # "getters are the "propper" way to get data out of a class
            print self.data
    
        def GetCVs(self):
            return self.cv1, self.cv2
    
    
    if __name__ == "__main__":
        inst1 = HasClassVars({})    # built with an empty dict of data
        inst2 = HasClassVars([])    # built with an empty list of data
    
        # it is legal to access the variables directly
        print inst1.cv1         # I once wrote a class in which all instance shared some data
        HasClassVars.cv1 = 3    # by using this technique
        print inst1.cv1
        print inst1.cv2
        inst1.cv1 = 7   # assigning an instance var of the same name overrides the classvar
        print inst2.cv1
        hasClassVars.cv1 = 12
        print inst1.cv1
    
        inst1.cv3 = 6   # Legal, but design-wise considered to be an "encapsulation violation"
                        # because with out special tricks (like my default value holder class)
                        # functions of this class won't be aware of its existance.
    
    
        print inst2.GetCVs() # Using getters avoids some pitfalls
        print inst1.GetCVs()

    Comment

    • bartonc
      Recognized Expert Expert
      • Sep 2006
      • 6478

      #3
      Not to confuse you, but I wrote a class that allows
      instance.prefix Anyname = value
      which returns values for Anyname.

      It's a variable size variable encapulator - fairly advanced stuff - which syncs to values in the Windows registry, using defaults that it holds if the registry key does not exist. The registry can also be updated from its values. It was quite fun to write. Check it out here.

      Comment

      • bartonc
        Recognized Expert Expert
        • Sep 2006
        • 6478

        #4
        Originally posted by bartonc
        This might help you get your mind around this issue:

        Code:
            inst1.cv1 = 7   # assigning an instance var of the same name overrides the classvar
        This is probably the best reason for using "getters" and "setters".

        Comment

        • true911m
          New Member
          • Dec 2006
          • 92

          #5
          Originally posted by bartonc
          This is probably the best reason for using "getters" and "setters".
          I got it.

          I guess that, although it's not an underlying tenet of OO programming, I prefer to place the responsibility for how programming elements are used on the programmer's shoulders, and so prefer any mechanism that is LESS restrictive instead of MORE restrictive. So, I was immediately drawn to the class variable approach for general assignments, even from within the instances.

          I see a couple drawbacks you pointed out, but on others I'm not so clear.

          If assigning to the class instead of the instance changes the value for all instances, I guess I see that as an optional benefit rather than a drawback. i.e., if it's not what the programmer intended, either 1) he wouldn't have done it, or b) the prog won't work as expected.

          As for the other point - assignment from outside "overrides" the value - does this mean that it simply reassigns the value to that (internal) variable, or does it mean that it destroys/hides that internal reference so that it can no longer be accessed because of the external one that has the same name?

          I like the getter code, and those simple registry references are very handy to have. Most stuff I've read on similar libs requires much more specific calls and references.

          Comment

          • bartonc
            Recognized Expert Expert
            • Sep 2006
            • 6478

            #6
            Originally posted by true911m
            As for the other point - assignment from outside "overrides" the value - does this mean that it simply reassigns the value to that (internal) variable, or does it mean that it destroys/hides that internal reference so that it can no longer be accessed because of the external one that has the same name?
            Hiding is probably a good term for what happens when an instance is assigned a variable with the same name as a class variable. All scope rules in python are created by the search algorithm used (look in scope a, if not found, look in scope b, and so on). So when the name is found in the instance, the search ends. The variable still exists in the class object and is still available to other instances which don't have their own version.

            Comment

            • bartonc
              Recognized Expert Expert
              • Sep 2006
              • 6478

              #7
              Originally posted by bartonc
              Hiding is probably a good term for what happens when an instance is assigned a variable with the same name as a class variable. All scope rules in python are created by the search algorithm used (look in scope a, if not found, look in scope b, and so on). So when the name is found in the instance, the search ends. The variable still exists in the class object and is still available to other instances which don't have their own version.
              This is the same as the mechanism used for class inheritance/override.

              Comment

              • bartonc
                Recognized Expert Expert
                • Sep 2006
                • 6478

                #8
                Originally posted by bartonc
                This is the same as the mechanism used for class inheritance/override.
                bumping tread due to relevance.

                Comment

                Working...