Python Forum

Full Version: How can I save a class as a module
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello pals;

I have been using C++ and just a newbie in python programming, however, it seem quite difficult for me to save my class in python as a module that can be reused in other programs.

In C++, all I would need to do is to save my class with any name of my choice and on the calling program; in the type the following in the header #include "name of my class" and that will be it. But in python it is very much different and I am confused about how I can even start it (but am pretty good at developing python classes).

Any reply that will be of help will be treated with gratitude. Thanks.
Create a file foo.py with the class definition:

class Foo:
   def __init__(self):
      pass
   def bar(self):
      pass
In file main.py import it:

import foo
myfoo = foo.Foo()

# -- or -- 
from foo import Foo
myfoo = Foo()
If that doesn't work, you have to post your code along with the error you're getting.
say file1 is MyClass.py and class name is MyClass and in that class you have a method named get_data_dict that returns a dictionary built in the class

to use that class in another module:
import MyClass

class SomeNewClass:
    def __init__(self):
        self.mc = MyClass.MyClass()

    def some_method(self):
       data_dict = self.mc.get_data_dict()