1

I wrote a class which looks like:

class EllipticCurve:
    points = []

    def generatePoints(a, b, p):
        ...

This generates correct set of points for the curves. I wanted to run a time test on different curves so wrote a main function as:

def main():
    for i in range(5):
        E = EllipticCurve(a, b, p) # with random values of a, b, p 
        E.generatePoints()

This generates the correct set of points for the first run, but during successive runs, the previous points are kept. Why?

For Example, after first run if i print E.points:

[(1, 2), (1, 3)] (say)

in the next run it prints:

[(1, 2), (1, 3), (1, 5), (1, 6)]

even though the first 2 tuples were not calculated this run.

msvalkon
  • 11,887
  • 2
  • 42
  • 38

2 Answers2

0

The points member declared that way has a class scope, i.e. it's shared for all instances.

Do this instead:

class EllipticCurve:
    def __init__(self):
        self.points = []

    def generatePoints(self, a, b, p):
        ... update self.points instead of EllipticCurve.points ...
6502
  • 112,025
  • 15
  • 165
  • 265
0

Because the points[] list doesn't get cleared during the lifecycle of your EllipticCurve class. It's similar to static field in Java. To make the list instance specific, you can e.g. create it in the constructor. See the difference between A and B:

class A(object):
    mylist = []

A.mylist
# []

A.mylist.append(1)
A.mylist
# [1]

a = A()
a.mylist
# [1]

class B(object):
    def __init__(self):
        self.mylist = []

B.mylist
# AttributeError: type object 'B' has no attribute 'mylist'

b= B()
b.mylist.append(1)
b.mylist
# [1]

b2 = B()
b2.mylist.append(2)
b2.mylist
# [2]

b.mylist
# [1]    
Danstahr
  • 4,190
  • 22
  • 38