0

I started creating an array, then i referenced its element with lists. Now I want to print the entire array (this is: all the lists on the array), i created a function "show" and "show array" but always print the last element of the array

IN:

class Test: pass def read(v, r): n = len(v) for i in range(0, n): v[i] = r v[i].number= 5+i v[i].name = i*2 v[i].author = i+6 v[i].genre = i*3 v[i].quantity = i+2 def show_array(v): n = len(v) for i in range(0, n): show(v[i]) def show(reg): print(reg.number, end=' ; ') print(reg.name, end=' ; ') print(reg.author, end=' ; ') print(reg.genre, end=' ; ') print(reg.quantity) def menu(): v = 2 * [None] t= Test() read(v, t) show_array(v) menu() 

OUT:

6 ; 2 ; 7 ; 3 ; 3 6 ; 2 ; 7 ; 3 ; 3 
3
  • FWIW, your "array" v is a list, so calling it an array is a bit confusing. Commented Sep 8, 2015 at 7:03
  • Pass r=Test and say v[i] = r() to create a new instance of Test Commented Sep 8, 2015 at 7:20
  • I did what you say Peter and worked. Thank you! Commented Sep 8, 2015 at 14:07

3 Answers 3

2

No, you are showing all elements of the array. They are all pointing to the same object so when you alter the object in your read loop, you change the object everywhere. You need to create a new Test object for each place in your array.

Sign up to request clarification or add additional context in comments.

1 Comment

You were right, I delete "t = Test()" and in "for" of "read" I put "v[i] = Test()" directly and worked :). Thanks!
0

Because this is only one t. First value is always coverd by last value.

You can write "print (v[i].name)" in "for" of "read()" and you can see the diffrence. You should create a new t.

1 Comment

I added a print in "read()" but seems ok. OUT: 5; 0; 6; 0; 2 6; 2; 7; 3; 3
0

I am not a python expert but u can try to make use of isinstance() this may help you to print all the values of a specified list by comparing the array value with list.If it is a list then print that particular list elements.If it is not a list then print the normal array value.

https://infohost.nmt.edu/tcc/help/pubs/python/web/isinstance-function.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.