Hello, I have a question concerning python and object instances. In the
sample program below, several instances of the same class are made one after
the other. I would expect that the values of "num" and "list" are reset to
"0" and "[]" with each new instance created. But why the heck does this work
like expected for "num" but not for "list"?!
I'm really stuck and confused. Does anybody know what the problem is?
-- Dominik
class MyClass:
num = 0
list = []
def setVar(self, i):
if self.list == []: self.list.append(i)
if self.num == 0: self.num = i
for i in range(0, 4):
obj = MyClass()
obj.setVar(i)
print obj.list
print obj.num
Program output:
[0]
0
[0]
1
[0]
2
[0]
3
Program output I would expect:
[0]
0
[1]
1
[2]
2
[3]
3 5 1364
In article <3f********@pfaff2.ethz.ch>, kaswoj <ka****@gmx.net> wrote: class MyClass: num = 0 list = []
def setVar(self, i): if self.list == []: self.list.append(i) if self.num == 0: self.num = i
for i in range(0, 4): obj = MyClass() obj.setVar(i) print obj.list print obj.num
[snip]
Program output I would expect: [0] 0 [1] 1 [2] 2 [3] 3
Try removing the "if self.list == []: " from setVar, and you'll get
this output:
[0]
0
[0]
1
[0]
2
[0]
3
[0]
0
[0, 1]
1
[0, 1, 2]
2
[0, 1, 2, 3]
3
I think your confusion comes from the fact that num and list class
variables (is that the right term?), not instance variables. That is,
there is only one "num" or "list", shared by all instances of MyClass.
The first object gets created and appends 0 to the list. After that,
the list is not empty, so nothing else is appended (and the list
remains [0]).
To get the output you expected, change the class definition to:
class MyClass:
def __init__(self):
self.num = 0
self.list = []
def setVar(self, i):
self.list.append(i)
if self.num == 0: self.num = i
-Mark
"kaswoj" <ka****@gmx.net> writes: Hello, I have a question concerning python and object instances. In the sample program below, several instances of the same class are made one after the other. I would expect that the values of "num" and "list" are reset to "0" and "[]" with each new instance created. But why the heck does this work like expected for "num" but not for "list"?! I'm really stuck and confused. Does anybody know what the problem is?
Yep, I should think so; short explanation follows (It's late so clarity and
accuracy might suffer).
-- Dominik
class MyClass:
# these two are *class* variables shared between all instances of the class
num = 0 list = []
def setVar(self, i): if self.list == []: self.list.append(i)
A) B)
This line looks up self.list twice (A) ,B) ). Since there is no instance
variable self.list, it resorts to the class variable MyClass.list. Then it
*mutates* it with append.
if self.num == 0: self.num = i
C) D)
This looks up self.num once and again resorts to the class variable ( C) ).
However assignment to self.XXX creates a new *binding* of a value to an
instance attribute name (even if there already is a class variable of the same
name). (Try adding the line ``print MyClass.num, self.num, MyClass.list,
self.list``)
I suspect what you want is:
class MyClass:
def __init__(self):
# run each time instance is created; viz. we create instance variables
self.num = 0
self.list = []
def setVar(self, i):
if self.list == []: self.list.append(i)
'as
"kaswoj" <ka****@gmx.net> wrote in message
news:3f********@pfaff2.ethz.ch... Hello, I have a question concerning python and object instances. In
the sample program below, several instances of the same class are made
one after the other. I would expect that the values of "num" and "list" are
reset to "0" and "[]" with each new instance created.
As far as I can think, Python never automatically resets anything.
That includes both default parameter values and class attributes used
as default instance attributes.
But why the heck does this work like expected for "num" but not for
"list"?!
You shadow 'num' and mutate 'list' (which shadows builtin list())
class MyClass: num = 0 list = []
def setVar(self, i): if self.list == []: self.list.append(i)
This executes as "if MyClass.list == []: MyClass.list.append[i]". On
the first call, [] is changed to [0] != [], so that is one and only
trigger and change.
if self.num == 0: self.num = i
This executes as "if MyClass.num == 0: instance.num=i". Since
MyClass.num remains the same, this always triggers.
for i in range(0, 4): obj = MyClass() obj.setVar(i) print obj.list # == print MyClass.list == [0] print obj.num
Program output: [0] 0 [0] 1 [0] 2 [0] 3
Exactly as explained.
Terry J. Reedy
Thanks a lot you guys, i understand it now.
I think too much in java, so I always get into trouble trying to write
object oriented python programs :)
-- Dominik I think too much in java, so I always get into trouble trying to write
object oriented python programs :)
Just add a bit of self-ishness! Or how about 'this':
class MyClass:
def __init__(this, i):
this.num = 0
this.lst = []
-- Dominik
Sarat This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Sybren Stuvel |
last post by:
Hi people,
I'm creating a program that can solve and create Sudoku puzzles. My
creation function needs to make a lot of copies of a puzzle. Until
now, I used copy.deepcopy(), but that's too...
|
by: xavier vazquez |
last post by:
I have a problem with a program that does not working properly...when the program run is suppose to generate a cross word puzzle , when the outcome show the letter of the words overlap one intop of...
|
by: xavier vazquez |
last post by:
have a problem with a program that does not working properly...when the program run is suppose to generate a cross word puzzle , when the outcome show the letter of the words overlap one intop of the...
|
by: oncue01 |
last post by:
Word Puzzle
Task
You are going to search M words in an N × N puzzle. The words may have
been placed in one of the four directions as from (i) left to right (E), (ii) right
to left (W), (iii) up...
|
by: honey777 |
last post by:
Problem: 15 Puzzle
This is a common puzzle with a 4x4 playing space with 15 tiles, numbered 1 through 15. One "spot" is always left blank. Here is an example of the puzzle:
The goal is to...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
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: 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: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
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...
| |