0

Is it possible (preserving all the class functionality) to write the class functions in separate files?

Below is an example:

TestClass.py:

class MyClass():
    def __init__(self, param1=1, param2=2, param3=3):
        self.param1, self.param2, self.param3 =param1, param2, param3,

    def ClassFun1(self, param1=2):
        return param1**2/self.param2

TestClass2.py:

def ClassFun2(self, param1=3):
    return param1*3/self.param2

Next, following this answer, I compile both files (I am too lazy to use import), create a class variable and try to use ClassFun2:

x=MyClass()
x.myMethod=ClassFun2
x.myMethod(2)

As a result, I get an error, since self in ClassFun2 is treated as a parameter, rather than class itself:

AttributeError: 'int' object has no attribute 'param2'

Is it possible to split class definition into several source files? It is possible in C++ and this is actually very convenient when working as a team.

martineau
  • 119,623
  • 25
  • 170
  • 301
Mikhail Genkin
  • 3,247
  • 4
  • 27
  • 47

1 Answers1

2

The variable x is an object of the class, not the class itself. You need to do:

x = MyClass
x.myMethod = ClassFun2

Notice that I didn't put () after MyClass. That returns the class itself, it doesn't return an instance of the class.

Then you need to create an instance to execute the method:

y = MyClass()
y.myMethod(2)
Barmar
  • 741,623
  • 53
  • 500
  • 612