Python Jumpstart by Building 10 Apps Transcripts
Chapter: App 7: Wizard Battle App
Lecture: Concept: Classes
Login or
purchase this course
to watch this video and the rest of the course contents.
0:01
Now that we've had a chance to work with classes in our wizard game, let's take a moment and look at the most common features
0:07
that appear and are used with classes. As you saw, we define all classes with the class keyword,
0:14
so here we are defining a creature class so we can say class creature, and like all code suits or blocks in Python
0:22
we define the rest of the class by saying colon and then indenting four spaces, everything that is indented, is part of the class,
0:30
so here you can see that we have two methods, one method called walk is a standard instance method if you will, and when you call it on an object
0:40
and instance of a creature you say creature.walk and it takes whatever the name of that creature is and it says,
0:47
you know, let's say it's toad, so toad walks around. See this yellow keyword self, this is a convention, it could be called anything,
0:54
in other languages it's called this and like C# or C++ but here we are calling self and its pass to all instance methods
1:02
and that's how we access the field, here we are saying self.name this is just a standard instance method,
1:09
the one above it is the initialzier, and you can tell that is a magic method because it has double underscores on both sides,
1:16
so typically this is referred to as "dunder" so here we would say __init__(), and this is actually not often directly called
1:25
but it is actually part of the initialization creation process of the creature, so when we create a new creature
1:31
we are going to actually pass this name and level and then we somewhat dynamically create the fields the name and the level on the self pointer.
1:40
Classes bundle together behavior and data, here the data is the name and the level of the creature and the behavior is its ability to walk around.
1:48
And these features of a class are the most common, but in fact classes are very rich in Python as we'll see
1:54
you can have inheritance, you can have what are called properties, you can have static methods, you can have class methods,
2:01
you can have static variables or fields on the class so we are just using sort of the most common stuff here in our game,
2:09
but you can go really deep with classes and actually do a ton.