A confusing problem with Python instance variable

Discuss how to use the Ren'Py engine to create visual novels and story-based games. New releases are announced in this section.
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.
Post Reply
Message
Author
Sanddman
Newbie
Posts: 12
Joined: Wed Dec 08, 2010 3:27 am
Contact:

A confusing problem with Python instance variable

#1 Post by Sanddman »

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?

fortaat
Regular
Posts: 183
Joined: Tue May 18, 2010 1:16 pm
Contact:

Re: A confusing problem with Python instance variable

#2 Post by fortaat »

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:

Code: Select all

import copy

class A:

    def __init__(self, Variable=[]):
        self.Variable = copy.deepcopy(Variable)

Sanddman
Newbie
Posts: 12
Joined: Wed Dec 08, 2010 3:27 am
Contact:

Re: A confusing problem with Python instance variable

#3 Post by Sanddman »

thanks! That IS a better solution !

Post Reply

Who is online

Users browsing this forum: AWizardWithWords, Bing [Bot], Semrush [Bot]