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.
7 2016
This might help you get your mind around this issue: - 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()
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.
This might help you get your mind around this issue: -
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".
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.
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.
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.
This is the same as the mechanism used for class inheritance/override.
bumping tread due to relevance.
Sign in to post your reply or Sign up for a free account.
Similar topics
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...
|
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
|
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...
|
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...
|
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...
|
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*...
|
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...
|
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>"...
|
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...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
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...
|
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...
|
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
|
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...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
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,...
|
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...
|
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...
| |