Hello I need an uninstantiated class attribute and I am doing this:
>>> class X:
... def __init__(self, y=None):
... self.y = list()
Is this ok? If no, is there another way of doing it. I can’t instantiate this attribute in __init__ cause I would be appending to this later.
Define the
yvar on the class-level attribute. You will need to initialize it to something, even it’s an empty list (as you were doing before).Update based on your comments:
You mentioned that you were mixed on the terminology (I’m assuming between class and instance variables), so here’s what’ll happen if you use this class (and is probably not what you want).
Notice that when you add a variable to the class it sticks around between constructions. In the previous code we instantiated the variable
xand the variablezas an instance of X. While we added to theyvariable in thezinstance, we still appended to the class variabley. Note on the very last line (X.y.append(4)) I append an item using a reference to the classX.What you probably want is based off of your original post:
Notice how a new list is created with each instance. When we create a new instance
zand try to append to theyvariable we only get the value that was appended, rather than keeping all of the existing additions to the list. In the last instantiation (t) example the constructor passes in theyparameter in it’s construction, and thus has the list[10]as it’syinstance variable.Hopefully that helps. Feel free to ask any more uncertainties as comments. Also, I would suggest reading up on the Python class documentation here.