Home > Net >  Python: How to use methods from another file
Python: How to use methods from another file

Time:11-15

I am kind of a beginner in python and stuck with the part where I have to access methods from a class which reside in a different file. Here, in File1 i am trying to access find_method from file2 to and do some operation and return values. But somehow its not accessing "find_method" from file2.

id_1.py (File1):
from base_file import base_file
class id_1:
  def condition():
     day_part_response = ...some response...
     current_time = ...some value...
     abc = basefile.find_method(x=day_part_response, y=current_time)

base_file.py (File2)
class basefile:
  def find_method(self, x, y):
     for day in day_response:
        start = day["start_time"]
        end = day["end_time"]

        if (condition):     -->(consider this condition is satisfied)
                
                self.start_time = start
                self.end_time = end
                day_id = day["_id"]
                self.entity_ID = day["entity_id"]
                self.restore = True
                self.create_entity()
                return self.start_time, self.end_time, day_id, self.day_part_entity_ID, self.restore

CodePudding user response:

You will need to import using from base_file import basefile. Make sure to use above import statement, your both files 1 & 2 are in same directory.

In base_file.py, check if for your given input satisfies the condition -

if start < end and start < store_time < end or \
                    end < start and not (end < store_time < start):

otherwise it won't return any result and None will get returned as default.

In id_1.py, check if you are creating instance of the class id_1 like -

id_1_instance = id_1()

and then call the condition method on the instance

id_1_instance.condition()

Since above call receives a returned value, make sure to print it so you can see the output.

CodePudding user response:

You should be doing: from base_file import basefile If 'base_file.py' is in the same directory as id_1.py then the import will work. If you put the class in a different directory, you need to add a line of code before the import, something like:

sys.path.append("/home/username/python/classes")

You should also take a look at https://peps.python.org/pep-0008/#class-names which gives you the recommended naming conventions such as: methods should be in the 'snake' format: def my_method().

Class names should follow the 'camelcase'. The class MyNewClass() should be saved in a file named: myNewClass.py So, you would do the import as: from myNewClass import MyNewClass.

I save all my classes in a single 'class' directory. Of course if you are using Windows, you would have to specify "C:\whatever".

Hope this helps!

  • Related