Reference and Parameter in Python

0

I have a class in Python that has a function that returns a triple (3 information together) and I wanted to create 4 different objects because I need 4 different triples. The point is that the values are accumulating and the 4th object has the information of it and the previous 3 others. Does anyone know why? That is, every time I call the function, the list (global in the class) is not overwritten.

class Anel():

    nomeResiduo = ""
    numCadeias = 1
    centroide = []

    def preencheAnel(self, residuo):

        i=0
        aux = residuo[0][4]

        while i < (len(residuo)):
            if ((i+1) < len(residuo)):
                if(aux != residuo[i+1][4]):
                    self.numCadeias += 1
                aux = residuo[i+1][4]
            i=i+1

        i = 0
        atomosPorCadeia = len(residuo)/self.numCadeias

        while i < self.numCadeias:
            centroide.append(Anel().calculaCentroide(residuo, self.numCadeias, i))
            i += 1

        self.nomeResiduo = residuo[0][2]

        return (self.nomeResiduo, self.numCadeias, centroide)
    
asked by anonymous 12.04.2017 / 00:16

1 answer

2

As discussed in the comments, you confused class attribute with instance attribute. When defining the attribute of the form:

class Foo:
    attribute = ["Hello"]

    def add(self, value):
        self.attribute.append(value)

We call it a class attribute and it will be common to all instances of it. For example, consider the two objects:

>>> foo1 = Foo()
>>> foo2 = Foo()

If we change the value of the attribute of an object, the other will be changed as well, since the attribute is of the class.

>>> foo1.add("Stack Overflow")
>>> print(foo2.attribute)
['Hello', 'Stack Overflow']

To get around this, you can set the attribute as an instance attribute by setting it within the instance's initializer:

class Foo:
    def __init__(self):
        self.attribute = ["Hello"]
    ...

In this way, changing the value of one object, the other will not be affected:

>>> foo1.add("Stack Overflow")
>>> print(foo2.attribute)
['Hello']

In your case, the attribute in question is centroide so you can do:

class Anel():

    def __init__(self):
        self.nomeResiduo = ""
        self.numCadeias  = 1
        self.centroide   = []
    ...

Or use the variables as locations to the method, if there is no need for them to be instance attributes.

    
12.04.2017 / 02:42