Inheritance in Python
You’re almost always using some form of inheritance within Python, even if you don’t explicitly declare it. To demonstrate that, I’m going to use the Python interactive shell. I’m going to start by creating a new class called
MyClass—a very creative name.
Now, I will instantiate this class into a new object called
c. Python has a built-in function called
dir(), which returns a list of all the members of the class you pass in. A class’s members are just the attributes and methods that make up the class, including the special
.__init__() method that’s used for object instantiation.
That’s probably not what you were expecting. What are all of these members with double underscores (
__), and where are they coming from? These members are actually all methods called magic methods, or dunder methods,
You might be able to guess what’s going on here, but let me explain. This
o object was instantiated from the
object class, which is super confusing considering we’ve been calling every instance of any class an object. Well, this
object class is not a class that we define ourselves.
It’s built into Python and it’s this
object class that defines these strange members that we’re seeing. And, as it turns out, every custom class that we create automatically inherits from this
object class behind the scenes, even if we don’t explicitly make it.
That explains why the
c object has all of these members too—it inherited it from the
object class. The extra members present in our custom class came from elsewhere, but that’s beyond the scope of this course.
03:27 If no code catches that exception object before it reaches the top, the program crashes and you’re left with a stack trace. If you’re interested in learning more about exceptions, we have a course for that, which I will link down in the video notes below.
It’s saying that our class must inherit from
BaseException is a built-in class provided for all error types. There are lots of classes that derive from
BaseException, such as
ArithmeticError, which means that we can use them in place of
SyntaxError inherits from
BaseException, it means
SyntaxError is a
BaseException because it inherits all of the members of
BaseException. What specific exception type you inherit from depends on the situation at hand.
BaseException is not supposed to be inherited from directly, so we’ll choose its next child, a class called
This is the class that the official documentation recommends inheriting from. I’ll redefine the
MyError class, but this time I’ll put the name of the class I want to inherit from in parentheses, after the class name.
but I want to do one more thing. Exceptions usually have some sort of message that’s intended to tell the user or developer what went wrong. The
Exception class contains an attribute for the message,
Become a Member to join the conversation.