kms
kms

Reputation: 2014

calling a method inside a class from a different file

I am trying to implement python classes and objects in my application code. Currently, I have a file that includes all the frequently used functions. I import them in another file.

funcs.py

class name1():

     def func1(x):

         return x

     def func2(y):

         return y

....

file1.py

from funcs import func1
from funcs import func2

I'd like to organize the code in class, method and attributes and then invoke them in different files.

How do I call a method within a class from another file? What changes do I need to make in funcs.py file?

Upvotes: 0

Views: 1540

Answers (1)

Ülephaze
Ülephaze

Reputation: 53

If you want to call a method within a class, first you have to instantiate an object of that class, and then call the method in reference to the object. Below is not an ideal implementation but it's just for example.
example.py

class MyClass:
    def my_method(self):
        print('something')

object1 = MyClass()
object1.my_method()

Then when you want to call the method in another file you have to first import them.
another.py

from .example import MyClass

object2 = MyClass()
object2.my_method()

If you just want to call the method without having to create an object first you can use @staticmethod.

class MyClass:
    @staticmethod
    def my_method(self):
        print('something')

MyClass.my_method()

Yet as I said this is not the ideal implementation. As @juanpa.arrivillaga said ideally you cannot just throw in any method and bundle them into a single class. The content of a class is all related to the object you want to define as a class.

Upvotes: 1

Related Questions