473,725 Members | 2,278 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Class Variable Access and Assignment

This has to do with class variables and instances variables.

Given the following:

<code>

class _class:
var = 0
#rest of the class

instance_b = _class()

_class.var=5

print instance_b.var # -> 5
print _class.var # -> 5

</code>

Initially this seems to make sense, note the difference between to last
two lines, one is refering to the class variable 'var' via the class
while the other refers to it via an instance.

However if one attempts the following:

<code>

instance_b.var = 1000 # -> _class.var = 5
_class.var = 9999 # -> _class.var = 9999

</code>

An obvious error occurs. When attempting to assign the class variable
via the instance it instead creates a new entry in that instance's
__dict__ and gives it the value. While this is allowed because of
pythons ability to dynamically add attributes to a instance however it
seems incorrect to have different behavior for different operations.

There are two possible fixes, either by prohibiting instance variables
with the same name as class variables, which would allow any reference
to an instance of the class assign/read the value of the variable. Or
to only allow class variables to be accessed via the class name itself.

Many thanks to elpargo and coke. elpargo assisted in fleshing out the
best way to present this.

perhaps this was intended, i was just wondering if anyone else had
noticed it, and if so what form would you consider to be 'proper'
either referring to class variables via the class itself or via
instances of that class. Any response would be greatly appreciated.
Graham

Nov 3 '05 #1
166 8638
On Thu, 03 Nov 2005 01:43:32 -0800, Graham wrote:

[snip]
print instance_b.var # -> 5
print _class.var # -> 5

</code>

Initially this seems to make sense, note the difference between to last
two lines, one is refering to the class variable 'var' via the class
while the other refers to it via an instance.
That's not correct. The line instance_b.var is referring to an instance
attribute. According to the usual Object Oriented model of inheritance, if
the instance does not have an attribute, the class is searched next.

So instance_b.var and _class.var are asking for two different things. The
first says, "Search the instance for attribute var, then the class." The
second says "Search the class."

BTW, a leading underscore is the convention for a private(ish) variable.
The convention for naming a variable after a reserved word is a trailing
underscore class_. In this case, there is also the convention that classes
should start with a capital, so you have Class and instance. (instance, of
course, is not a reserved word.)

However if one attempts the following:

<code>

instance_b.var = 1000 # -> _class.var = 5
_class.var = 9999 # -> _class.var = 9999

</code>

An obvious error occurs.
I see no error. No exception is raised when I try it: I get the expected
results. Assigning to an instance assigns to the instance, assigning to
the class assigns to the class. That's normal OO behaviour.

When attempting to assign the class variable
via the instance it instead creates a new entry in that instance's
__dict__ and gives it the value.
You might *want* to assign to the class attribute, but that's not what you
are doing. You are assigning to the instance.

Admittedly, it might not be the behaviour you expect, but it is the
standard behaviour in (as far as I know) all OO languages.

If you want to assign to the class attribute, you either assign to the
class directly, or use instance_b.__cl ass__.var.

While this is allowed because of
pythons ability to dynamically add attributes to a instance however it
seems incorrect to have different behavior for different operations.
Surely you can't mean that? Why would you want different operations to
have the same behaviour?

There are two possible fixes, either by prohibiting instance variables
with the same name as class variables, which would allow any reference
to an instance of the class assign/read the value of the variable. Or
to only allow class variables to be accessed via the class name itself.


There is also a third fix: understand Python's OO model, especially
inheritance, so that normal behaviour no longer surprises you.
--
Steven.

Nov 3 '05 #2
Op 2005-11-03, Steven D'Aprano schreef <st***@REMOVETH IScyber.com.au> :
There are two possible fixes, either by prohibiting instance variables
with the same name as class variables, which would allow any reference
to an instance of the class assign/read the value of the variable. Or
to only allow class variables to be accessed via the class name itself.


There is also a third fix: understand Python's OO model, especially
inheritance, so that normal behaviour no longer surprises you.


No matter wat the OO model is, I don't think the following code
exhibits sane behaviour:

class A:
a = 1

b = A()
b.a += 2
print b.a
print A.a

Which results in

3
1

--
Antoon Pardon
Nov 3 '05 #3
Antoon Pardon <ap*****@forel. vub.ac.be> writes:
Op 2005-11-03, Steven D'Aprano schreef <st***@REMOVETH IScyber.com.au> :
There are two possible fixes, either by prohibiting instance variables
with the same name as class variables, which would allow any reference
to an instance of the class assign/read the value of the variable. Or
to only allow class variables to be accessed via the class name itself.


There is also a third fix: understand Python's OO model, especially
inheritance, so that normal behaviour no longer surprises you.


No matter wat the OO model is, I don't think the following code
exhibits sane behaviour:

class A:
a = 1

b = A()
b.a += 2
print b.a
print A.a

Which results in

3
1


I find it confusing at first, but I do understand what happens :-)

But really, what should be done different here?

S.
Nov 3 '05 #4
Antoon Pardon wrote:
Op 2005-11-03, Steven D'Aprano schreef <st***@REMOVETH IScyber.com.au> :

There are two possible fixes, either by prohibiting instance variables
with the same name as class variables, which would allow any reference
to an instance of the class assign/read the value of the variable. Or
to only allow class variables to be accessed via the class name itself.


There is also a third fix: understand Python's OO model, especially
inheritance , so that normal behaviour no longer surprises you.

No matter wat the OO model is, I don't think the following code
exhibits sane behaviour:

class A:
a = 1

b = A()
b.a += 2
print b.a
print A.a

Which results in

3
1

I don't suppose you'd care to enlighten us on what you'd regard as the
superior outcome?

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Nov 3 '05 #5
Op 2005-11-03, Stefan Arentz schreef <st***********@ gmail.com>:
Antoon Pardon <ap*****@forel. vub.ac.be> writes:
Op 2005-11-03, Steven D'Aprano schreef <st***@REMOVETH IScyber.com.au> :
>> There are two possible fixes, either by prohibiting instance variables
>> with the same name as class variables, which would allow any reference
>> to an instance of the class assign/read the value of the variable. Or
>> to only allow class variables to be accessed via the class name itself.
>
> There is also a third fix: understand Python's OO model, especially
> inheritance, so that normal behaviour no longer surprises you.
No matter wat the OO model is, I don't think the following code
exhibits sane behaviour:

class A:
a = 1

b = A()
b.a += 2
print b.a
print A.a

Which results in

3
1


I find it confusing at first, but I do understand what happens :-)


I understand what happens too, that doesn't make it sane behaviour.
But really, what should be done different here?


I don't care what should be different. But a line with only one
referent to an object in it, shouldn't be referring to two different
objects.

In the line: b.a += 2, the b.a should be refering to the class variable
or the object variable but not both. So either it could raise an
attribute error or add two to the class variable.

Sure one could object to those sematics too, but IMO they are preferable
to what we have now.

--
Antoon Pardon
Nov 3 '05 #6
Steve Holden <st***@holdenwe b.com> writes:
class A:
a = 1
b = A()
b.a += 2
print b.a
print A.a
Which results in
3
1

I don't suppose you'd care to enlighten us on what you'd regard as the
superior outcome?


class A:
a = []
b = A()
b.append(3)
print b.a
print a.a

Compare and contrast.
Nov 3 '05 #7
On Thu, 03 Nov 2005 11:55:06 +0000, Antoon Pardon wrote:
No matter wat the OO model is, I don't think the following code
exhibits sane behaviour:

class A:
a = 1

b = A()
b.a += 2
print b.a
print A.a

Which results in

3
1


Seems perfectly sane to me.

What would you expect to get if you wrote b.a = b.a + 2? Why do you expect
b.a += 2 to give a different result?

Since ints are immutable objects, you shouldn't expect the value of b.a
to be modified in place, and so there is an assignment to b.a, not A.a.

On the other hand, if this happened:

py> class A:
.... a = []
....
py> b = A()
py> b.a.append(None )
py> print b.a, A.a
[None], []

*then* you should be surprised.

(Note that this is not what happens: you get [None], [None] as expected.
The difference is that append modifies the mutable list in place.)

--
Steven.

Nov 3 '05 #8
Antoon Pardon <ap*****@forel. vub.ac.be> writes:

....
No matter wat the OO model is, I don't think the following code
exhibits sane behaviour:

class A:
a = 1

b = A()
b.a += 2
print b.a
print A.a

Which results in

3
1
I find it confusing at first, but I do understand what happens :-)


I understand what happens too, that doesn't make it sane behaviour.
But really, what should be done different here?


I don't care what should be different. But a line with only one
referent to an object in it, shouldn't be referring to two different
objects.


It doesn't.
In the line: b.a += 2, the b.a should be refering to the class variable
or the object variable but not both. So either it could raise an
attribute error or add two to the class variable.


It does exactly what you say. It adds 2 to the a *instance variable* of
the object instance in 'b'. It doesn't touch the *class variable* A.a
which is still 1.

S.
Nov 3 '05 #9
Op 2005-11-03, Stefan Arentz schreef <st***********@ gmail.com>:
Antoon Pardon <ap*****@forel. vub.ac.be> writes:

...
>> No matter wat the OO model is, I don't think the following code
>> exhibits sane behaviour:
>>
>> class A:
>> a = 1
>>
>> b = A()
>> b.a += 2
>> print b.a
>> print A.a
>>
>> Which results in
>>
>> 3
>> 1
>
> I find it confusing at first, but I do understand what happens :-)
I understand what happens too, that doesn't make it sane behaviour.
> But really, what should be done different here?


I don't care what should be different. But a line with only one
referent to an object in it, shouldn't be referring to two different
objects.


It doesn't.


Yes it does. If the b.a refers to the instance variable, then an
AttributeError should be raised, because the instance variable doesn't
exist yet, so you can't add two to it.

If the b.a refers to the class variable then two should be added to it.

Neither happens instead we get some hybrid in which an instance varible
is created that gets the value of class variable incrented by two.
In the line: b.a += 2, the b.a should be refering to the class variable
or the object variable but not both. So either it could raise an
attribute error or add two to the class variable.


It does exactly what you say. It adds 2 to the a *instance variable* of
the object instance in 'b'.


There is no instance variable at that point. How can it add 2, to
something that doesn't exist at the moment.
It doesn't touch the *class variable* A.a which is still 1.


But it accesses the class variable.

--
Antoon Pardon
Nov 3 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

106
5571
by: A | last post by:
Hi, I have always been taught to use an inialization list for initialising data members of a class. I realize that initialsizing primitives and pointers use an inialization list is exactly the same as an assignment, but for class types it has a different effect - it calls the copy constructor. My question is when to not use an initalisation list for initialising data members of a class?
5
2145
by: xuatla | last post by:
Hi, I encountered the following compile error of c++ and hope to get your help. test2.cpp: In member function `CTest CTest::operator+=(CTest&)': test2.cpp:79: error: no match for 'operator=' in '*this = CTest::operator+(CTest&)((+t2))' test2.cpp:49: error: candidates are: CTest CTest::operator=(CTest&) make: *** Error 1
5
8732
by: Chris | last post by:
Hi, I don't get the difference between a struct and a class ! ok, I know that a struct is a value type, the other a reference type, I understand the technical differences between both, but conceptually speaking : when do I define something as 'struct' and when as 'class' ? for example : if I want to represent a 'Time' thing, containing : - data members : hours, mins, secs
9
1930
by: NevilleDNZ | last post by:
Can anyone explain why "begin B: 123" prints, but 456 doesn't? $ /usr/bin/python2.3 x1x2.py begin A: Pre B: 123 456 begin B: 123 Traceback (most recent call last): File "x1x2.py", line 13, in ? A() File "x1x2.py", line 11, in A
14
2637
by: lovecreatesbea... | last post by:
Could you tell me how many class members the C++ language synthesizes for a class type? Which members in a class aren't derived from parent classes? I have read the book The C++ Programming Language, but there isn't a detail and complete description on all the class members, aren't they important to class composing? Could you explain the special class behavior in detail? Thank you very much.
20
4038
by: tshad | last post by:
Using VS 2003, I am trying to take a class that I created to create new variable types to handle nulls and track changes to standard variable types. This is for use with database variables. This tells me if a variable has changed, give me the original and current value, and whether the current value and original value is/was null or not. This one works fine but is recreating the same methods over and over for each variable type. ...
20
1475
by: d.s. | last post by:
I've got an app with two classes, and one class (InventoryInfoClass) is an object within the other class (InventoryItem). I'm running into problems with trying to access (get/set) a private variable within the included class (InventoryInfo) from the "including" class (InventoryItem). Here's the code, trimmed down. I've included ********* at the start of the first line that's blowing up on me. I'm sure others that try to access the...
16
3439
by: John Doe | last post by:
Hi, I wrote a small class to enumerate available networks on a smartphone : class CNetwork { public: CNetwork() {}; CNetwork(CString& netName, GUID netguid): _netname(netName), _netguid(netguid) {}
0
8752
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9179
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8099
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3228
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.