Use a Dunder Class Reference
Restart, and I will create the
d again. Okay, of course now we’re running into an error because I added
trait as a required parameter. So now it’s not just
"brown" and called
"Puppy", but it’s also not lazy at all.
Okay, so we have
d.trait. We have our industrious brown dog Puppy, and if I
Dog now, the
Dog instance, I should get back the string, and it says
"The industrious brown dog Puppy
jumps over the lazy dog." That’s the output that I was hoping for.
But now I want to redo the little problem that I did earlier. If I assign a new instance attribute on this
Dog object that shadows, the class attribute
.animal_type, then Python’s going to pick up that one first, and it’s not going to go back to the class attribute
01:36 I want to make sure that in this output, I always still know that the instance is actually a dog and not a fox, even if I would accidentally add this instance attribute that shadows the class attribute.
So instead of
Animal.animal_type, I’m going to say
self.__class__.animal_type, and this
self.__class__ is going to always refer to the class that this instance was modeled from. In the
Dog class, this is going to be
Dog, and in the
Pig class it’s going to be
Pig, et cetera, so that the
.animal_type is actually going to be the class attribute, even if you accidentally override it and put an instance attribute of the same name in there. Long story short, let’s try it out.
Try it out first.
print(d) still working.
"The industrious brown dog
Puppy jumps over the lazy dog." Great. And then if I create this instance attribute,
.animal_type, that shadows the class attribute, now if I
So, a little hoop that I jumped through here just to make sure that I can also
print() out what type of animal an animal is and to keep this class attribute around without having to do a lot of code duplication.
There might be other ways to solve this, but I think this works well, and it was a nice chance to talk about some potential issues with class attributes. All right,
Pig can all have
.trait and can
print() out nicely. Next, we also need some methods.
Become a Member to join the conversation.