473,394 Members | 1,693 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Diffs class vars vs. instance vars?

true911m
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.
Dec 16 '06 #1
7 2016
bartonc
6,596 Expert 4TB
This might help you get your mind around this issue:

Expand|Select|Wrap|Line Numbers
  1. class HasClassVars(object):
  2.     # class variables
  3.     cv1 = 4
  4.     cv2 = 8
  5.     def __init__(self, data):     # Constructor args often become instance variables
  6.         self.data = data
  7.  
  8.     def PrintData(self):  # "getters are the "propper" way to get data out of a class
  9.         print self.data
  10.  
  11.     def GetCVs(self):
  12.         return self.cv1, self.cv2
  13.  
  14.  
  15. if __name__ == "__main__":
  16.     inst1 = HasClassVars({})    # built with an empty dict of data
  17.     inst2 = HasClassVars([])    # built with an empty list of data
  18.  
  19.     # it is legal to access the variables directly
  20.     print inst1.cv1         # I once wrote a class in which all instance shared some data
  21.     HasClassVars.cv1 = 3    # by using this technique
  22.     print inst1.cv1
  23.     print inst1.cv2
  24.     inst1.cv1 = 7   # assigning an instance var of the same name overrides the classvar
  25.     print inst2.cv1
  26.     hasClassVars.cv1 = 12
  27.     print inst1.cv1
  28.  
  29.     inst1.cv3 = 6   # Legal, but design-wise considered to be an "encapsulation violation"
  30.                     # because with out special tricks (like my default value holder class)
  31.                     # functions of this class won't be aware of its existance.
  32.  
  33.  
  34.     print inst2.GetCVs() # Using getters avoids some pitfalls
  35.     print inst1.GetCVs()
Dec 16 '06 #2
bartonc
6,596 Expert 4TB
Not to confuse you, but I wrote a class that allows
instance.prefixAnyname = 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.
Dec 16 '06 #3
bartonc
6,596 Expert 4TB
This might help you get your mind around this issue:

Expand|Select|Wrap|Line Numbers
  1.     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".
Dec 16 '06 #4
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.
Dec 16 '06 #5
bartonc
6,596 Expert 4TB
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.
Dec 17 '06 #6
bartonc
6,596 Expert 4TB
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.
Dec 17 '06 #7
bartonc
6,596 Expert 4TB
This is the same as the mechanism used for class inheritance/override.
bumping tread due to relevance.
Jan 27 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

50
by: Dan Perl | last post by:
There is something with initializing mutable class attributes that I am struggling with. I'll use an example to explain: class Father: attr1=None # this is OK attr2= # this is wrong...
166
by: Graham | last post by:
This has to do with class variables and instances variables. Given the following: <code> class _class: var = 0 #rest of the class
3
by: Mustafa Rabie | last post by:
I have a registeration which is divided on 3 pages, i want to have a class that i can create on the 1st page, collect the data from page 1 and add the values to vars in the class, then page 2 and...
10
by: David Hirschfield | last post by:
Here's a strange concept that I don't really know how to implement, but I suspect can be implemented via descriptors or metaclasses somehow: I want a class that, when instantiated, only defines...
10
by: John A Grandy | last post by:
Say I have Class1 which contains static Class2 var1 = new Class2(); Is Class2 constructor code only executed if var1 is referenced in the code-execution path ? Or is Class2 constructor code...
0
by: Ray Schumacher | last post by:
Thanks Larry, My depth really only gets to ~3: package module module error_module and usually not that. It is shallow, with >hundred methods (mainly serial protocol defs for LX*...
9
by: glomde | last post by:
Hi I wonder if you can set what subclass a class should have at instance creation. The problem is that I have something like: class CoreLang(): def AssignVar(self, var, value): pass class...
0
by: Fredrik Lundh | last post by:
Robert Rawlins wrote: Name or namespace? You can access the class name from an instance via the __class__ attribute: .... def __repr__(self): .... return "<%s instance at %x>"...
1
by: BrendanC | last post by:
I'm trying to understand reflection/introspection in Python. How can I identify the the type of attribute (e.g. instance var) in a class? The following returns all the class attributes (methods and...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.