I'm thinking that a short explanation of the difference between class and instance attributes in Python might be helpful to you.
When you write code like so:
class Graphics:
screen_size = (1024, 768)
The class Graphics
is actually an object itself -- a class object. Because you defined screen_size
inside of it, screen_size
is an attribute of the Graphics
object. You can see this in the following:
assert Graphics.screen_size == (1024, 768)
In Python, these class objects can be used like functions -- just use the invocation syntax:
g = Graphics()
g
is called an "instance" of the class Graphics
. When you create instances of a class, all attribute lookups that don't match attributes of the instance look at the attributes of the class object next. That's why this lookup works:
assert g.screen_size == (1024, 768)
If we add an attribute to the instance with the same name, however, the lookup on the instance will succeed, and it won't have to go looking to the class object. You basically "mask" the class object's value with a value set directly on the instance. Note that this doesn't change the value of the attribute in the class object:
g.screen_size = (1400, 1050)
assert g.screen_size == (1400, 1050)
assert Graphics.screen_size == (1024, 768)
So, what you're doing in your __init__
method is exactly what we did above: setting an attribute of the instance, self
.
class Graphics:
screen_size = (1024, 768)
def __init__(self):
self.screen_size = (1400, 1050)
g = Graphics()
assert Graphics.screen_size == (1024, 768)
assert g.screen_size == (1400, 1050)
The value Graphics.screen_size
can be used anywhere after this class definition, as shown with the first assert statement in the above snippet.
Edit: And don't forget to check out the Python Tutorial's section on classes, which covers all this and more.