Create many classes within a same python module

Besides creating a class within another class we can also create many classes within the same python module. Let us take a look at how to create a python module with many classes in it.

Start a new Eclipse’s project as before then create this module :- doubleclassdemo.py and input below python script into it.

class FirstClass(object):
    
    def __init__(self, welcome = "welcome to first class server!"):
        print(welcome)
        
class SecondClass(object):

    def __init__(self, welcome = "welcome to the second class server!"):
        print(welcome)

As you can see we have created two classes in one module. Next create another python module and name it mainserver.py then enter below script into it.

import doubleclassdemo 

if __name__ == '__main__':
    print(doubleclassdemo.FirstClass())
    print(doubleclassdemo.SecondClass())

Run the mainserver.py module.

As you can see we have imported the doubleclassdemo module into this module and then create a new instance for both classes within the doubleclassdemo module inside that print method which will first call the __init__ method of each class to print out the welcome message and then will call the __str__ method to return the memory address of each class and print it out!

welcome to first class server!
<doubleclassdemo.FirstClass object at 0x00FE5C10>
welcome to the second class server!
<doubleclassdemo.SecondClass object at 0x00FE5C10>

Do you realize that both classes do share the same memory address? Hmmm…interesting.