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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With