Creating the Dog Class (Solution)
Here I am in the new file that I saved on my computer, and I called it
Doggo.py. I’m going to start by recapping the tasks that I basically have for the
Dog class. So I should build a
I think these are the tasks. Let’s get started. So I’ll start by building the
Dog class, using the
class keyword and then the name of the class, which I will use in cap case. So starting off with a capital letter.
And I’ll add a
pass keyword down here to say that I want to add some more information into the class. So that’s my
Dog class without anything, but I do have a
Dog class. I’m going to get rid of this first comment.
01:45 If I put a variable right underneath the class, then it’s part of the class. So then it becomes a class attribute and not specific to an instance of the class. So defining a variable like this makes it a class variable.
Make sure that you keep your code indented to make it part of the
Dog. And now I need to create the initializer method,
.__init__(), which is going to run every time that I create a new instance of
Dog, I need to define this method,
We’re going to need a
name and then
age. So creating a method signature that takes three parameters,
age, means that when I actually create an instance of
Dog, we’re going to have to pass two attributes,
And that should be it. So by defining the
.__init__() in this way, what I say is that every
Dog instance that gets created has two arguments that you need to pass when you create an instance. Otherwise, it’s going to fail.
I’m going to use another dunder method,
__str__(self), always the first one. And here I don’t need to pass anything else because I will just access the instance attributes and then create a string and return that specific string. So that’s going to be printed when I call
print() and pass it an instance of the
Dog class. Here I will return—let’s use is an f-string, easier to format—
self.name, So the name of that specific dog.
This is not going to be a special method like the other two. This is actually going to be a public method of that class, and I’m calling it
.speak(), and it takes
self and it also takes a
sound. So again,
self is the reference to the instance itself.
You’re not going to have to pass that because Python does that for you. But then it takes one argument, and then I want to again return an f-string that gives the information of who it is, so the name of the dog, and then it says whatever sound you passed in. Note that here, you don’t use
self.sound, right, because this is not an instance attribute, but this is just an argument that you are passing to this method when you’re calling it. And I think that should be it.
Become a Member to join the conversation.