A friend posed an interesting question the other day.
Is it possible to create a class within a class in Python?
Honestly, I had no idea. It might be possible but what would I gain from doing so. Just off the the top of my head, I can imagine the code looking like this:
And I can imagine that you'd have to input
Of course the true scientist would explore this possibility.
And turns out, you can create a class in a class. I will now coin the term describing such a practice as class-ception.
It also turns out that this is particularly useless; the only reason anyone might do this is because they only need their nested class for this one program and it doesn't require variables outside of the nested class.
What do I mean? Well, taking the example above, you might think that any variable defined in Shape or Square exists in the counterpart's namespace. It doesn't. You can't call Shape methods if the object is a Square and to call Square methods when the object is a Shape requires the Square prefix. So basically it has all the limitations of a module plus a bit of added confusion.
Moral of story: Don't bother nesting classes in Python.
Is it possible to create a class within a class in Python?
Honestly, I had no idea. It might be possible but what would I gain from doing so. Just off the the top of my head, I can imagine the code looking like this:
class Shape:
def __init__(self):
...
...
class Square:
def__init__(self):
...
...
And I can imagine that you'd have to input
Shape.Square()
to create a Square object, which essentially seems the same as a method or a module.Of course the true scientist would explore this possibility.
And turns out, you can create a class in a class. I will now coin the term describing such a practice as class-ception.
It also turns out that this is particularly useless; the only reason anyone might do this is because they only need their nested class for this one program and it doesn't require variables outside of the nested class.
What do I mean? Well, taking the example above, you might think that any variable defined in Shape or Square exists in the counterpart's namespace. It doesn't. You can't call Shape methods if the object is a Square and to call Square methods when the object is a Shape requires the Square prefix. So basically it has all the limitations of a module plus a bit of added confusion.
Moral of story: Don't bother nesting classes in Python.