473,756 Members | 1,881 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
166 8651
Op 2005-11-07, Steve Holden schreef <st***@holdenwe b.com>:
Antoon Pardon wrote:
Op 2005-11-05, Steven D'Aprano schreef <st***@REMOVETH IScyber.com.au> :
On Fri, 04 Nov 2005 12:10:11 +0000, Antoon Pardon wrote:
>There are good usage cases for the current inheritance behaviour. I asked
>before what usage case or cases you have for your desired behaviour, and
>you haven't answered. Perhaps you missed the question? Perhaps you haven't
>had a chance to reply yet? Or perhaps you have no usage case for the
>behaviou r you want.

There are good use cases for a lot of things python doesn't provide.
There are good use cases for writable closures, but python doesn't
provide it, shrug, I can live with that. Use cases is a red herring
here.

Is that a round-about way of saying that you really have no idea of
whether, how or when your proposed behaviour would be useful?

I am not proposing specific behaviour. Because if I do, you will
just try to argue how much worst my proposed behaviour is.

Whether or not I can come up with a better proposal is irrelevant
to how sane the current behaviour is.

If you can't provide a superior alternative then you have little right
to be questioning the present behavior.


Nonesense. Unable to produce a superior alternative doesn't make
one unable to evaluate.
Personally , I think that when you are proposing a major change to a
language that would break the way inheritance works, there should be more
benefits to the new way than the old way.

How many times do I have to repeat myself. I'm not proposing a change
to the language.

So you have a clear impression that Python's current behavior is
unsatisfactory enough to be called "unsane" which,


You are generalizing my words to the point they no longer
reasonably resemble what I wrote.
If you're just trolling, you've done a great job of it because you fooled
me well and good. But if you are serious in your criticism about the
behaviour, then stop mucking about and tell us what the behaviour should
be. Otherwise your criticism isn't going to have any practical effect on
the language at all.


I wasn't trolling. I just threw in an off hand remark. That you got so
heated up about that remark is not my responsibility. I'm not trolling
because I'm willing to defend my remark and I don't intend to get
people to get heated up about it. I just don't hold back because
people may get heated up about it.

The defense of your original remark implies very strongly that it wasn't
offhand, and that you are indeed trolling. Hence the reduction in the
frequency of my replies. You make it more and more difficult to take you
seriously.


Fine that goes both ways. I don't mind not being taken serious by people
I have trouble taking serious my self. No doubt that goes for you too.

So I propose we don't react to each other any longer, since there
would be very little purpose in it.
Particularly since you have now resorted to a defense which
involves refusing to define a non-existent word in any but the vaguest
terms - you are trying to specify a position on the imaginary continuum
of sanity, but you don't say how close to which end you are trying to
specify. This puts you somewhere between "barmy" and "crackpot" on my
own personal scale.
If you are serious about wanting the behaviour changed, and not just
whining, then somebody has to come up with an alternative behaviour that
is better.

If I would be whining I would want the behaviour changed. I would just
keep complaining about it until someone else would have changed it.

Instead you just keep complaining about it, full stop.


No I don't keep complaining about. I just defend my claim.
Since we are all
now fully aware of your opinions, couldn't you just shut up, or do we
have to send you to your room without any supper? Whine, whine, whine.
Well since you are aware of my opinion, why don't you just ignore
any new articles of mine in this thread and go on, instead of whining
about the fact that I care to defend what I wrote but won't put
more fuel on the fire by starting my idea about superior behaviour
which would only make this thread live longer without any chance
of coming to a shared conclusion.
Every time I reply to you my spell checker looks at your name and shows
me a dialog with an "ignore all" button on it. I have this increasing
suspicion that it's trying to tell me something.


Well maybe you should listen to it. It seems damn obvious neither of
us has anything interresting to say to the other.

--
Antoon Pardon
Nov 7 '05 #161
On Mon, 07 Nov 2005 12:05:40 +0100, Magnus Lycka <ly***@carmen.s e> wrote:
First of all, I've still not heard any sensible suggestions
about a saner behaviour for augmented assignment or for the
way Python searches the class scope after the instance scope. A nit, but a sizeable one: For new-style classes, the class scope
is searched first for a descriptor that may trump the instance logic.
What do you suggest?

Today, x += n acts just as x = x + n if x is immutable.
Do you suggest that this should change? A descriptor allows you to make it do as you like, so it's
a matter of discussing default behavior, not what you
are locked into (although costs re optimization could be a topic).
Today, instance.var will look for var in the class
scope if it didn't find it in the instance scope. Do
you propose to change this? It is already changed, for new-style classes. It is only if
a data descriptor is NOT found in the class hierarchy that
an existing instance variable is accessed as "usual".

Or, do you propose that we should have some second order
effect that makes the combination of instance.var += n
work in such a way that these features are no longer
orthogonal?

I don't think he is proposing anything, just defending against
what he considers misinterpretati ons of what he is saying.
Given how hard it is to say ANYTHING and be understood EXACTLY,
this tends towards a pursuit of quantum nits ;-)
I suspect we all experience the emotions relevant to being misunderstood;
we just stop at different nit granularities (modulo horn locking ;-)

Regards,
Bengt Richter
Nov 7 '05 #162
On 7 Nov 2005 08:38:49 GMT, Antoon Pardon <ap*****@forel. vub.ac.be> wrote:
Op 2005-11-04, Magnus Lycka schreef <ly***@carmen.s e>:
[...] Sure, Python has evolved and grown for about 15 years, and
backward compatibility has always been an issue, but the
management and development of Python is dynamic and fairly
open-minded. If there had been an obvious way to change this
in a way that solved more problems than it caused, I suspect
that change would have happened already.


Fine I can live with that.

Amen ;-)

Regards,
Bengt Richter
Nov 7 '05 #163
Antoon Pardon wrote:
Op 2005-11-04, Christopher Subich schreef <cs************ ****@spam.subic h.block.com>:
it's the Python
idiosyncrac y about operations on mutable types. In this case, +=
mutates an object, while + returns a new one -- as by definition, for
mutables.

It is the combination of the two.

If python had chosen for an approach like function namespaces, the
problem wouldn't have occured either. What would have happened then
is that the compilor would have noticed the a.x on the right hand
side and based on that fact would then have deciced that all a.x
references should be instance reference (at least in that function
block). The a.x += ... would then result in an AttributeError being raised.


Problem:
"""
class B:
x = 1
classx = b()
instx = b()
instx.x = 5

def addtox(o):
o.x += 1

addtox(instx)
print B.x # 1
print instx.x # 6; we both agree on this one
addtox(classx) # You argue this should AttributeError
print B.x # ?! -- 1 currently, you argue 2 if no error
print class.x # we both agree 2, if no error
"""

a.x is /not/ a namespace issue at all; it's an attribute issue.

..x is not a name, it is an attribute. Python namespaces are lexically
scoped, not dynamically scoped; if, as you argue, .x should be a name in
a namespace, then you argue above that addtox in the above should work
on instx but fail on classx. But this /cannot be determined at compile
time/, because the attribute space is attached to the object passed in
as the parameter.

I repeat: this is not a name issue at all, it is an attribute issue.
Python's behaviour is counterintuitiv e from some angles, but it is the
only behaviour that is consistent with attributes in general, given the
signature of __iadd__ as-is.

You may prefer the current behaviour over this, but that is not the
point. The point is that resolution of name spaces does play its
role in this problem.
There are no name spaces.


It also has little to do with mutable vs immutable types.
Someone could implement an immutable type, but take advantage
of some implemtation details to change the value inplace
in the __iadd__ method. Such an immutable type would show
the same problems.


Immutable? I do not think that word means what you think it means.
Nov 7 '05 #164
Op 2005-11-07, Christopher Subich schreef <cs************ ****@spam.subic h.block.com>:
Antoon Pardon wrote:
Op 2005-11-04, Christopher Subich schreef <cs************ ****@spam.subic h.block.com>:
it's the Python
idiosyncra cy about operations on mutable types. In this case, +=
mutates an object, while + returns a new one -- as by definition, for
mutables.

It is the combination of the two.

If python had chosen for an approach like function namespaces, the
problem wouldn't have occured either. What would have happened then
is that the compilor would have noticed the a.x on the right hand
side and based on that fact would then have deciced that all a.x
references should be instance reference (at least in that function
block). The a.x += ... would then result in an AttributeError being raised.


Problem:
"""
class B:
x = 1
classx = b()
instx = b()
instx.x = 5

def addtox(o):
o.x += 1

addtox(instx)
print B.x # 1
print instx.x # 6; we both agree on this one
addtox(classx) # You argue this should AttributeError
print B.x # ?! -- 1 currently, you argue 2 if no error
print class.x # we both agree 2, if no error
"""

a.x is /not/ a namespace issue at all; it's an attribute issue.

.x is not a name, it is an attribute.


This may be a meaningfull distinction in the current implementation
but IMO it is less meaningfull to make such a distinction conceptually.

x is a name and proceeding it with a. is just a way of deciding in
which namespace the x is to be searched.
Python namespaces are lexically
scoped, not dynamically scoped; if, as you argue, .x should be a name in
a namespace, then you argue above that addtox in the above should work
on instx but fail on classx. But this /cannot be determined at compile
time/, because the attribute space is attached to the object passed in
as the parameter.
That depends on what you allow in the langauge. Allowing declarations
in the language could take care of that.

You could also decide scope per scope what is to be happend. If
somewhere in the scope there is a line a.x = ..., then within that
scope all 'a.x' refer to the object. In other scope a.x is decide
as it is now.
I repeat: this is not a name issue at all, it is an attribute issue.
Why make such a big distinction between the two?
Python's behaviour is counterintuitiv e from some angles, but it is the
only behaviour that is consistent with attributes in general, given the
signature of __iadd__ as-is.


If you mean the only behaviour that is consistent with the current
python attribute implementation. I can accept that. But as you have
worded it, it seems way to general, almost claiming that any language
that does it differently is not consistent. Maybe I misunderstood.

--
Antoon Pardon
Nov 8 '05 #165
Antoon Pardon wrote:
Fine that goes both ways. I don't mind not being taken serious by people
I have trouble taking serious my self. No doubt that goes for you too.


You know Antoon, these internet communities aren't really like
Speaker Corner in Hyde Park. You earn respect based on your merits,
not from the stubborn persistence in you arguments.

Steve has written a very good book on Python, he's worked a lot
with Python conferences, and helped people on comp.lang.pytho n
for years etc. He has earned his respect.

You are fighting wind mills, bickering about things that you
don't have any solutions for. It's possible that you have just
not realized how Python handles objects, names and classes, but I
can't understand what you are trying to accomplish. What can you
possibly try to convey that you haven't already stated? It's
as if you've got stuck in this thread. In the real world, I
haven't heard of anyone ever having had problems with this.

Isn't it better to let it go and to spend your time on something
constructive?

I recently heard a priest say, that the difference between the
saint and the fanatic is that the fanatic tries to remove the
evil in the world, while the saint tries to remove the evil in
himself.

Just as introspection is useful both in fighting evil and in
Python programming, I think it's useful when we get into heated
discussions. I've always loved heated discussions, but over time,
I've come to realize that the best thing that can happen in such
a discussion is to realize that I was wrong. Then I've learnt
something! If I don't change my mind, I'm just standing still.
In that case, it might be useful for someone else, if she or he
learnt something from it, but the best thing is if I learn
something.

This thread is all to infected to lead to good things. Hopefully
you'll learn something about communication from it, but the price
has been higher than you might be aware of right now.
Nov 8 '05 #166
Op 2005-11-08, Magnus Lycka schreef <ly***@carmen.s e>:
Antoon Pardon wrote:
Fine that goes both ways. I don't mind not being taken serious by people
I have trouble taking serious my self. No doubt that goes for you too.
You know Antoon, these internet communities aren't really like
Speaker Corner in Hyde Park. You earn respect based on your merits,
not from the stubborn persistence in you arguments.

Steve has written a very good book on Python, he's worked a lot
with Python conferences, and helped people on comp.lang.pytho n
for years etc. He has earned his respect.


So? Steve can be very good at explaining what python is and
how it behaves and at the same time have poor arguments why
this would be good langauge design.

So although he may have earned his respect in the first,
that doesn't mean I have to take him seriously in the
other.
You are fighting wind mills, bickering about things that you
don't have any solutions for.
People should know what they want. If one dares to propose
an alternative here, chances are that you get told to
search a language that behaves as you want, if you don't
you get blamed you don't have a solution.

The only acceptable behaviour, seems to keep quiet about
things where one thinks python could be improved.
It's possible that you have just
not realized how Python handles objects, names and classes, but I
can't understand what you are trying to accomplish. What can you
possibly try to convey that you haven't already stated? It's
as if you've got stuck in this thread. In the real world, I
haven't heard of anyone ever having had problems with this.
Well in the real world nobody seemed to have problems with
the lack of a condtional expression either. Each time someone
brought it up, they were told it wasn't necessary anyway and
how you could simulate it, with some caveat, by using 'and'
and 'or'.

Until it seems one of the developers got bitten by an elusive
bug caused by such a caveat and suddenly there will be a
condional expression in the next version.

So, that we haven't heard of anyone ever having a problem
with it doesn't contradict, that it may one day be the
cause of a very elusive bug.
This thread is all to infected to lead to good things. Hopefully
you'll learn something about communication from it, but the price
has been higher than you might be aware of right now.


Shrug, this is usenet, not my social life.

--
Antoon Pardon
Nov 8 '05 #167

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

Similar topics

106
5589
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
2148
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
2641
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
4042
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
1480
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
3445
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
9462
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9287
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
10046
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...
0
9722
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8723
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...
1
7259
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6542
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
5318
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3817
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

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.