Apr-20-2018, 05:53 PM
(Apr-19-2018, 08:09 PM)RaphaelMG Wrote: Im used to C (C# and C++)
Ok, so what you're doing, in terms of those other languages, is having a static variable
position
that's unbound from any instance. In python, they're called class attributes/methods instead of static, but it's essentially the same thing. In order to have instance variables, they'd need to be defined in the __init__
method, not outside of there.Here's some example code to try to show the difference:
>>> class Spam: ... # class attribute, shared by all instances ... things = [] ... def add(self, thing): ... self.things.append(thing) ... return self.things ... >>> eggs = Spam() >>> eggs.add("first") ['first'] >>> ham = Spam() >>> ham.add("second") ['first', 'second'] >>> Spam.things ['first', 'second'] >>> >>> class Bike: ... def __init__(self): ... self.things = [] ... def add(self, thing): ... self.things.append(thing) ... return self.things ... >>> two_wheels = Bike() >>> two_wheels.add("first") ['first'] >>> four_wheels = Bike() >>> four_wheels.add("second") ['second'] >>> Bike.things Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: type object 'Bike' has no attribute 'things'