Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I call a member function from another file in python

I am trying to create a multi-file environment for my project. The File structure is as such

project_folder
   |- FileA.py
   |- FileB.py

The FileA.py has mainly the script in it and also I have improted FileB here
FileA.py

import os,sys
from FileB import temp_class as T

// lines of code 
str = "somestring"
A, B, C = T.func(str)

// lines of code

FileB.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import os,sys

class temp_class:
    def func(self, S):
        //lines of code
        return (someA,someB,someC)

But I am getting the error as

TypeError: unbound method func() must be called with temp_class instance as first argument (got str instance instead)

>Solution :

You just need to instantiate it: T_inst = T(), and then use T_inst.func().

To expand: the error message tells you that it expects to find an instance of T (temp_class) as its first argument. When you call a method of a class instance, that very instance is passed as the first argument (usually called "self"). In this case you tried to invoke it as a method of the class itself (like a static method) so this doesn’t happen, and self instead was assigned the string that you passed (with the second argument getting None instead of a string).

If you don’t want to instantiate the class then you could either declare func a static method (or in the docs here) of temp_class, or simply make temp_class a module instead of a class (i.e, define its "methods" outside of any class, with the hierarchical structure provided by the way you structure your modules; in your case, to obtain behavior identical to that which you seem to be going for: a directory called FileB that contains a __init__.py file (to make it function as a module) and a temp_class.py file with the function func defined within it).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading