Skip to content Skip to sidebar Skip to footer

Is It Possible To Define A Function In A Class

I have a problem with my python code specialy when I'm trying to define a function in a Class. Indeed, I want to call this function (which is in a file i called BC.py) in my main p

Solution 1:

You should call it this way:

from BC import *
A=BC()
C=A.func1(x)

Edit for comment:

Please take care of the code format:

class real :
    def __init__(self):
        self.nmodes = 4
        self.L_ch = 1
        self.w = 2

    def func1(self,x):
        self.k_ch=self.nmodes*self.L_ch*self.w
        f=x**3+4*x*self.k_ch+15*self.k_ch
        return f

Solution 2:

Call the function this way (recommended):

A = BC()
C = A.func1(x)

or this other (less used and not recommended, just mentioned as information):

C = BC.func1(A, x)

Note: I would recommend you to rename your file with a name different than the class BC, because it confuses Python. Also, don't forget to declare x.


Post a Comment for "Is It Possible To Define A Function In A Class"