Loading video player…

Defining Classes in Python

00:00 So far you’ve learned that classes are the blueprints for objects, but how do you define a class in Python? The simplest possible class definition could look like this: class Crew: pass.

00:11 You define a class using the class keyword. By the way, in Python it is convention to use title case for classes, so that is why the C in Crew should be capitalized.

00:21 And be sure to indent the contents of the class four spaces. In this example, you would use the pass statement as a placeholder for the actual contents of the class to avoid an error.

00:30 Then you can instantiate, that is, create an instance of the class by calling it with parentheses, for example, crew_instance = Crew(). Open up the REPL and we’ll play around with this a little.

00:44 To practice working with objects, imagine you’re making a game about space exploration. In such a game, you might find it useful to have a class that models starships, space vessels.

00:53 So to start, you’re going to use the class keyword:

00:57 class Starship: and for now, the class body will be the pass keyword.

01:03 I’m recording this as Python version 3.14 is pretty new, and I’m loving the improved syntax highlighting in the REPL. If you’re on a different version, it will probably look different, but don’t worry, it’s just cosmetic.

01:14 Even with only these two lines of code, you can create instances of Starship. Try it by calling Starship().

01:22 The return value, which is evaluated by the REPL and displayed is <__main__.Starship object at 0x...> at some memory address.

01:29 This is the default behavior for how Python describes user-defined objects. And pay attention to what happens if you call Starship() again.

01:39 You’ll see that the memory address is different, because a new object is created each time, which makes sense, right? Instances should be distinct. Of course, you’ll usually want to assign your objects to variables.

01:51 So create two new Starship instances. For fun, let’s call them voyager and galactica.

02:00 And you can use the built-in type() function to see, yes, they are Starship objects. type(voyager) returns <class '__main__.Starship'>. type(galactica) returns the same.

02:12 Finally, to be sure that they are discrete objects, use the equality operator to compare the two:

02:18 voyager == galactica returns False. They are two separate objects in memory. Okay, so admittedly your Starship class is not much of a blueprint so far. These objects have neither behaviors nor properties.

02:33 You could make as many Crew instances as you want, but you wouldn’t be giving them their own attributes. To do that, you’ll need to add a little more code to the class definition.

02:42 See what exactly in the next lesson.

Become a Member to join the conversation.