Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language 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.

Class Attributes

00:00 Welcome to lesson three in Object-Oriented Programming in Python versus Java. In your last lesson, you discovered how to create instance attributes in Python. Now we will look at class attributes.

00:14 In Java, we use the keyword static to indicate a class field, so this statement placed with the other field definitions would create a class field with a value of 4 called wheels.

00:29 This would be the same value shared by any instance of the class that we create. In Python, class attributes are created by defining a variable outside of any method, usually occurring before any of the methods.

00:48 So here, in this new version of my Python class Car, I have created a class attribute called wheels and I’ve assigned it a value of 4. We don’t do anything in the .__init__() method.

01:03 We wouldn’t do anything in the constructor for a Java class. But now this gives an attribute that all objects of class Car are going to share.

01:16 To see how that works, let’s go ahead and create a Car.

01:23 And just like instance attributes, I use the dot (.) operator to access a class attribute. So I’m going to say print(f"My car has"), and then I can say f"{my_car.wheels} wheels".

01:45 And My car has 4 wheels. If you don’t have any objects created, you can refer to the class by first saying the filename—module name, more appropriately…

02:05 So we can say All cars have 4 wheels. In Python, an object can actually change its own value of a class attribute, not affecting the attributes of other objects already created or yet to be created.

02:26 So, let me make my pickup truck again.

02:32 I have a red Chevy S-10. I can say f"My pickup has {my_pickup.wheels} wheels". Now let’s suppose we convert this to a dually. I’m going to say my_pickup.wheels = 6.

02:55 I don’t recommend it, but we can reassign the value of a class attribute for a specific object. So now I can do that last print statement, f"My pickup has"

03:14 and now it has 6 wheels, but my_car

03:25 still has 4 wheels. In this lesson, we learned about class attributes. In our next lesson, we’ll learn how Python deals with visibility when everything in Python is public.

Become a Member to join the conversation.