I have seen nested for loops, while loops, functions,
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:
def __init__(self, string):
self.string = string
def __str__(self, string):
def __add__(self, *string_to_add):
new_string = self.string
for string in string_toa_add:
new_string += string
def __init__(self, num):
self.num = num
def __add__(self, *nums_to_add):
total = self.num
for num in nums_to_add:
total += num
# String will only be accessible in the Integer class:
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
# The Integer class also supports += because the class has implemented the __add__ dunder method:
one += 1
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
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?
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.