simani simani - 4 months ago 7
Python Question

What is the issue with displaying data in this code?

class s(object):
def vrod(self):
self.name=(input("enter name:"))
self.stno=int(input("enter stno:"))
self.score=int(input("enter score:"))

def dis(self):
j=0
while j<3:
print("enter name:",self.name,"enter stno:",self.stno,"enter score:",self.score)
j+=1


y=[]
j=0
st=s()

while j<3:
st.vrod()
y.append(st)
j+=1

st.dis()


I want to display information that I enter, but I cannot. You suppose that I run that and enter name, student number and score. Then, I only receive information from the third person which is tripled. Why and how can I eliminate problem?
Thanks

Answer

There are a couple of issues that need to be addressed:

  1. The st object is created once and then used multiple times in the while loop. This calls the same method of the same object multiple times, so the previous information is lost.
  2. The st object is being appended to the array multiple times. Because it is the same object being appended, if the object is updated, all if the elements in the array are updated with the same information.
  3. In the dis method, it appears what you want to do is iterate over the array and show all of the inputs received. The function is a member of an object, however, and the object has no knowledge of the other instantiated objects. What dis should do instead is only print the data related to a single object and then have external code call that method on each object.
  4. Your code never actually uses the array that it is trying to use to store previous information. This shows that you do not have a good understanding of how arrays, objects, and scope works. I would take a look at some resources for learning more about Object Oriented Programming (OOP) and Python. For example: http://www.tutorialspoint.com/python/python_classes_objects.htm


Here is some updated code that will do what you are looking for:

class s(object):
    def vrod(self):
        self.name=(input("enter name:"))
        self.stno=int(input("enter stno:"))
        self.score=int(input("enter score:"))

    def dis(self):
        print("enter name:",self.name,"enter stno:",self.stno,"enter score:",self.score)


y=[]
j=0

while j<3:
    st = s()
    st.vrod()
    y.append(st)
    j+=1

for st in y:
    st.dis()
Comments