Understanding Class and Instance Attributes
In this short lesson, you’re going to be understanding class and instance attributes and what the difference is between them. Take a look at this code. Got a class here,
Doggo, and you’ve got something that looks like a variable declaration here, where it says
species = "Canis familiaris". And this isn’t in any method, so it’s not in the
.__init__() method, the constructor. It’s at the, say, root level of the class indentation here, at the class level.
00:28 Then within the constructor method, you have some more attributes, which will become insurance attributes. What you have here are class attributes and instance attributes.
00:40 The class attribute is outside any method, whereas the instance attributes are within the constructor.
Take a look at this other example. You’ve got a class,
Point. It has a class attribute of
dimensions = 2, so all points will have two dimensions, at least in this model.
You could have a point in three dimensions or even four dimensions, but here you’re going to specify that their dimensions are
2, and you want all instances to have two dimensions, or at least the ones that are derived from this class or that are instantiated from this class.
Then within the constructor method, you have two instance attributes that will only live on the instances of the
Point. To summarize that, an instance attribute’s value is specific to a particular instance.
01:33 So if you instantiate two different objects and give them different attribute values, they will be unique to each instance, and they won’t be accessible from each instance. A class attribute, on the other hand, is available from both the class itself and all instances derived from that class.
01:53 So even if you’re dealing with an instance or if you don’t have any instances, you’re still able to access a class attribute.
Become a Member to join the conversation.