Python Forum
How can I save a class as a module
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I save a class as a module
#1
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.
Reply
#2
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.
Reply
#3
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()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to save to multiple locations during save cubangt 1 544 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  How to read module/class from list of strings? popular_dog 1 471 Oct-04-2023, 03:08 PM
Last Post: deanhystad
  My code displays too much output when importing class from a module lil_e 4 1,154 Oct-22-2022, 12:56 AM
Last Post: Larz60+
Question How to move a class to a custom module? python300 4 1,551 Mar-08-2022, 09:19 PM
Last Post: python300
  Error when refering to class defined in 'main' in an imported module HeRo 2 2,379 Apr-13-2021, 07:22 PM
Last Post: HeRo
  How to save a class object to a file? SheeppOSU 2 3,742 Jun-22-2019, 11:54 PM
Last Post: metulburr
  [Python Class] save method output to global file/list Vijay 3 5,045 Dec-23-2017, 03:20 AM
Last Post: Vijay

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020