E.g.
Create a python class say A
Class A:
def __init__(self, Variable=[]):
self.Variable=Variable
If I create a few instances without specifying Variable, say
X = A()
Y = A()
then X.Variable.append(something) will add that something to Y even though I defined Variable to be an instance variable. If I add
if Variable:
self.Variable=Variable
Else:
self.Variable = []
then the problem is solved.
I refuse to believe python is that dumb...Or am I just not following the right format?
A confusing problem with Python instance variable
Forum rules
This is the right place for Ren'Py help. Please ask one question per thread, use a descriptive subject like 'NotFound error in option.rpy' , and include all the relevant information - especially any relevant code and traceback messages. Use the code tag to format scripts.
This is the right place for Ren'Py help. Please ask one question per thread, use a descriptive subject like 'NotFound error in option.rpy' , and include all the relevant information - especially any relevant code and traceback messages. Use the code tag to format scripts.
Re: A confusing problem with Python instance variable
The problem with:
self.Variable=Variable
Is that every instance will be linked to the Variable dictionary. Every change you do to Variable would reflect on every instance. The following line:
self.Variable = []
Solved your problem because it initialized every instance with a different empty dictionary.
An easy solution would be to copy the dictionary upon initialization, and thus each instance would have its own copy of Variable:
self.Variable=Variable
Is that every instance will be linked to the Variable dictionary. Every change you do to Variable would reflect on every instance. The following line:
self.Variable = []
Solved your problem because it initialized every instance with a different empty dictionary.
An easy solution would be to copy the dictionary upon initialization, and thus each instance would have its own copy of Variable:
Code: Select all
import copy
class A:
def __init__(self, Variable=[]):
self.Variable = copy.deepcopy(Variable)
Re: A confusing problem with Python instance variable
thanks! That IS a better solution !
Who is online
Users browsing this forum: AWizardWithWords, Bing [Bot], Semrush [Bot]