1

I'm trying to have a class (dprObject) that is a container for several dprVariables each variable has a list with integers (for now) but when I change something to one variable, it changes to all the other variables

in this case, the output I get is

score: 5, 6, 3, 4, position: 5, 6, 3, 4,

but I want to see

score: 5, 6, position: 3, 4,

#!/usr/bin/python3

import pprint

def main(): 
    d = dprObject() #new dpr object
    score = dprVariable(d, "score") #new dpr variable
    score.set(5) #set value
    score.set(6)

    position = dprVariable(d, "position")
    position.set(3)
    position.set(4)

    print(d)
    print("done")

class dprObject:
    var = [] 
    t = 0
    def __init__(self):
        pass

    def __str__(self):
        toReturn = ""
        for v in self.var:
            toReturn += v.toString()
        return toReturn

    def tick(self):
        self.t += 1

    def addVariable(self,v):
        self.var.append(v)


class dprVariable:
    name = ""
    value = None
    val = []

    def __init__(self,d,name):
        self.name = name
        d.addVariable(self)

    def __str__(self):
        return self.toString()

    def toString(self):
        toReturn = self.name + ": "
        for v in self.val:
            toReturn += str(v) + ", "
        return toReturn

    def set (self, value):
        self.value = value
        self.val.append(value)

#class DprValue:



if __name__ == "__main__":
    main()

any help would be appreciated thanks

1 Answer 1

1

This code:

class dprVariable:
    ...
    val = []

makes val a class variable, shared between all instances of dprVariable. To have one val per instance, you need to do this:

class dprVariable:
    def __init__(self, ...):
        self.val = []

(dprObject has the same problem.)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.