473,804 Members | 3,475 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Magic class member variable initialization with lists

Hi, I reported a bug to the bugtracker (issue 1443), but it was
rejected with the comment:

"Go ask on c.l.py why this is not a bug"

After decrypting c.l.py to the name of this group, I'll do as I was
told so nicely, because I really think it is a misconcept, and cost me
two days because I couldn't believe it.

So here's the problem:
The Initialization of member variables with lists leads to strange
behavior.

The member variable is common to each instance of a class, if the
datatype is a list-Object (and presumable any other PyObject)

Example:
#-------------------------------------------------------
class Proof:
a=[]
b=[]

def __init__(self):
print self.a, self.b, self
self.a.append(" STICKYARRAY")
self.b=["NONSTICKY ASSIGN"]

if __name__ == "__main__":
p1=Proof()
p2=Proof()
#-------------------------------------------------------

The execution of this results in:
>[] [] <__main__.Pro of instance at 0x00BA7120>
['STICKYARRAY'] [] <__main__.Pro of instance at 0x00BA7148>
So the initialized list a is the same in both instances, but they are
completely different objects.

Well, I can think of the coders problem, that when creating the
object, always the same copy of the list object is being taken which
has once been defined, but it doesn't makes sense, because they are
not really static like C++, because as soon as you reassign them, they
are lost.

Bye,
Neo
Nov 15 '07 #1
1 1682
This is the expected behaviour. The reference on classes (http://
docs.python.org/ref/class.html) says:
Variables defined in the class definition are class variables;
they are shared by all instances. To define instance variables,
they must be given a value in the __init__() method or in
another method. Both class and instance variables are
accessible through the notation ``self.name'', and an instance
variable hides a class variable with the same name when
accessed in this way.
In your example, 'a' is a class variable, so it's shared by all
instances. 'b' is also a class variable, but in the __init__ method
you create an instance variable with the same name 'b', which takes
precedence over the class-level variable, so 'b' isn't shared.

I think what you need is:

class Proof:
def __init__(self):
self.a = []
self.b = []
# other things

Regards,
Marek
Nov 15 '07 #2

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

Similar topics

106
5620
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?
3
3618
by: DanielBradley | last post by:
Hello all, I have recently been porting code from Linux to cygwin and came across a problem with static const class members (discussed below). I am seeking to determine whether I am programming non-standard C++ or if the problem lies elsewhere. To summarize static const class members are not being accessed properly when accessed from a DLL by another external object file (not within the DLL). It only occurs when the static const...
5
5923
by: surrealtrauma | last post by:
the requirement is : Create a class called Rational (rational.h) for performing arithmetic with fractions. Write a program to test your class. Use Integer variables to represent the private data of the class – the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should contain default values in case no initializers are provided and should...
5
1880
by: Randy | last post by:
Hi, When a class contains another class as a member variable, e.g., class ClassA { int a; public :
17
1582
by: Amchi | last post by:
Alright .... this makes no sense ... Declared a class 'diskStorage' in a header ...diskStorage.h Defined it's contructor and methods ... in diskStorage.cpp Included diskStorage header in a another class ...(server.h) and then tried to declare a variable of type 'diskStorage' ... like this ( inside server.h ) diskStorage local_disk;
14
1887
by: Glen Dayton | last post by:
While looking at some old code I ran across a snippet that increments a pointer to access different members of a structure: .... struct Badness { std::string m_begin; std::string m_param1; std::string m_param2; std::string m_end;
8
8934
by: Per Bull Holmen | last post by:
Hey Im new to c++, so bear with me. I'm used to other OO languages, where it is possible to have class-level initialization functions, that initialize the CLASS rather than an instance of it. Like, for instance the Objective-C method: +(void)initialize Which has the following characteristics: It is guaranteed to be run
9
8903
by: Jess | last post by:
Hello, I was told that if I declare a static class constant like this: class A{ static const int x = 10; }; then the above statement is a declaration rather than a definition. As I've *defined* "x"'s value to be 10, isn't above statement a
15
7876
by: akomiakov | last post by:
Is there a technical reason why one can't initialize a cost static non- integral data member in a class?
0
9708
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
10589
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
10327
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
10085
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
9161
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
7625
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
6857
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
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3828
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.