Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Understanding Class and Instance Attributes

00:00 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.

00:48 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.

01:00 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.

01:16 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.