I have a class with a number of attributes. Could someone please clarify the differences between setting attributes like a,b,c below and x,y,z. I understand that if you arguments to come in they obviously must be in the init, however, just for setting a number default variables, which is preferred and what are the pros and cons.
class Foo(object):
a = 'Hello'
b = 1
c = False
def __init__(self):
self.x = 'World'
self.y = 2
self.z = True
Variables
a,b, andcare class variables. They’re evaluated and set once, when the class is first created. Variablesx,y, andzare instance variables, which are evaluated and set whenever an object of that class is instantiated.In general, you use class variables if the same values are going to be used by every instance of the class, and only needs to be calculated once. You use instance variables for variables that are going to be different for each instance of that class.
You can access class variables through the instance variable syntax
self.a, but the object in question is being shared between all instances of the class. This doesn’t affect much when using immutable data types such as integers or strings, but when using mutable data types such as lists, appending toself.awould cause all instances to see the newly-appended value.Some examples from IDLE are probably helpful in understanding this: