Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining and Calling a Function within a Python Class

Tags:

python

I'm creating a class and I'm hoping to call a user-defined function within a method for that class. I'd also like to define the function within the class definition. However, when I call the class, I get the error message name *whatever function* is not defined.

For instance, something like this:

class ExampleClass():

    def __init__(self, number):
        self.number = number

    def plus_2_times_4(x):
        return(4*(x + 2))

    def arithmetic(self):
        return(plus_2_times_4(self.number))

But when I call:

instance = ExampleClass(number = 4)
instance.arithmetic() 

I get the error message.

So basically I want to define the function in one step (def plus_2_times_4) and use the function when defining a method in another step (def arithmetic...). Is this possible?

Thanks so much in advance!

like image 661
Danny Avatar asked Jul 12 '26 12:07

Danny


2 Answers

Define and call plus_2_times_4 with self, namely:

class ExampleClass():

    def __init__(self, number):
        self.number = number

    def plus_2_times_4(self,x):
        return(4*(x + 2))

    def arithmetic(self):
        return(self.plus_2_times_4(self.number))

This will work.

like image 130
muskrat Avatar answered Jul 14 '26 00:07

muskrat


Call the method using ExampleClass.plus_2_times_4:

class ExampleClass():

    def __init__(self, number):
        self.number = number

    def plus_2_times_4(x):
        return(4*(x + 2))

    def arithmetic(self):
        return(ExampleClass.plus_2_times_4(self.number))

Alternatively, use the @staticmethod decorator and call the method using the normal method calling syntax:

class ExampleClass():

    def __init__(self, number):
        self.number = number

    @staticmethod
    def plus_2_times_4(x):
        return(4*(x + 2))

    def arithmetic(self):
        return(self.plus_2_times_4(self.number))

The @staticmethod decorator ensures that self will never be implicitly passed in, like it normally is for methods.

like image 40
ItsTimmy Avatar answered Jul 14 '26 01:07

ItsTimmy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!