Classes Inside Classes: Nested Classes

I have seen nested for loops, while loops, functions, if statements, else statements. I wondered weeks ago, what about nested classes(I haven’t seen it before except when I wrote this post).
Can you do this, how might it be useful:

class Integer: class String: def __init__(self, string): self.string = string def __str__(self, string): return self.string def __add__(self, *string_to_add): new_string = self.string for string in string_toa_add: new_string += string return new_string def __init__(self, num): self.num = num def __str__(self): return str(self.num) def __add__(self, *nums_to_add): total = self.num for num in nums_to_add: total += num return total # String will only be accessible in the Integer class: try: print(String(1)) except: print("The String class does not exist in the global namespace.") one = Integer(1) # This doesn't change one since the __add__ dunder method of the Integer class doesn't directly modify one: one + 1 print(one) # The Integer class also supports += because the class has implemented the __add__ dunder method: one += 1 print(one)

?
That is my Integer class I started today to practise classes and also to show you nested classes. I made the __add__ dunder method in both classes to not change the it because I want it to behave like a builtin data type and if I wanted to I could use like I demonstrated I could use +=. I could still use inheritance for to achieve this.

You’d need a good reason to use it (considering how common and useful polymorphism is).

Semantically, I’ll pick at your example: A class Integer respresents an abstract template for integers (that is, the term class is being used as a concept of "collection of the type Integer"). To say that such a class has within it a class String suggests that all integers contain an abstract template for strings. The problem is that the definition of the template for String is completely independent of Integer. That is, the concept of String exists without Integer, and is useful outside the realm of Integer.

So for the idea to work it has to overcome a few checks:

  • does it make semantic sense?
  • is it a pragmatic way to achieve a goal? (are there better ways?)
  • reasonably speaking, can another programmer come in and understand the idea relatively quickly?
3 Likes

I was using that as an example not that I would choose to use it. Maybe it might be useful if you have a class and in that class you want a class that is only related to the outer class.