Declaring a variable in a class (outside of a function): all class functions can access it (basically a public variable)
Declaring a variable inside a function insid
Declaring a variable at the top level of the class is like declaring a static or class variable. Qualifying it with self is declaring an instance variable. Class variables can be modified by referring to them by class name (e.g. Class.x = 5
) and all instances will inherit these changes. Instance variables are private to an instance and can only be modified by that instance.
You can achieve some level of access control using underscores. See private variables in the Python tutorial. By convention, variables starting with one underscore, e.g. _foo
are non-public parts of an API, and names starting with two underscores e.g. __foo
will have it's name mangled to be _classname__foo
.