python - Adding new objects in a list, all the objects look like the last one -


this question has answer here:

i'm making first program in python. need add objects list, , create these objects inside loop. problem is, after filling list, if check value of object, last object added.

class clsnumeros:      numero = 4     oper = [int() in range(5)]      def __init__(self, op1, op2, op3, op4):         self.oper[1] = op1         self.oper[2] = op2         self.oper[3] = op3         self.oper[4] = op4      def countoperaciones():         return 5      def getvaloroper(self, idxoper):         num = self.oper[idxoper]          if num == 1:             return num         elif num == 2:             return sqrt(num)         elif num == 3:             return factorial(num)         elif num == 4:             return 4/10         elif num == 5:             return sqrt(0.4)      def getexproper(self, idxoper):         num = self.oper[idxoper]          if num == 1:             return num         elif num == 2:             return "r(" + num + ")"         elif num == 3:             return num + "!"         elif num == 4:             return "0.4"         elif num == 5:             return "r(0.4)"      def display(self):          txt = ""          x in range(1, 5):             txt = txt + str(self.oper[x])             txt = txt + " ___ "          print (txt)    def generanumeros():     c = []     idx = [int() in range(5)]     = 0     idx[1] = 1     idx[2] = 1     idx[3] = 1     idx[4] = 1     looping = 1     n = 0      while looping == 1:         num = clsnumeros(idx[1], idx[2], idx[3], idx[4])         c.append(num)         n = n + 1         idx[4] = idx[4] + 1         in range (4, 1, -1):             if idx[i] > clsnumeros.countoperaciones():                 idx[i] = 1             idx[i-1] = idx[i-1] + 1         if idx[1] > clsnumeros.countoperaciones():             looping = 0          c[5].display()  # displaying object number 5. of them last 1      return numeros         

what wrong? can create objects inside loop , expect them unique? idea works fine on asp.net.

thanks!

the problem here:

class clsnumeros:      oper = [int() in range(5)] 

class variables evaluated once, @ moment of class definition. therefore, 1 instance of list created here. fix initialising oper in constructor instead.

other issues:

  • you can 0 instead of int()
  • you can [0]*5 instead of [0 in range(5)]
  • naming conventions: python uses method_name , classname, it's follow them
  • get habit of writing class clsnumeros(object), because other (older) syntax results in "old-style" class in python behaves bit differently
  • you can simplify method display using str.join method, example '__'.join(items)

Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -