Reputation: 532
I'm sure this is well understood, but even the examples I see I have trouble understanding how to use functions defined within a particular class.
The simple example I've made is as follows (make a function add_one
that adds 1 to a given input number and then use that function in another function add_two
):
class TestPassingFunctions:
def __init__(self, number):
self.number = number
def add_one(self, number):
return number + 1
def add_two(self, number):
new_value = self.add_one(number) + 1
return new_value
TestPassingFunctions.add_two(2)
This returns:
TypeError: add_two() missing 1 required positional argument: 'number'
From what I've read, it looks the class is interpreting the 2
as the self
parameter. As is probably obvious, I don't entirely understand when/how I should be using the initialization with __init__
. Up until this point, I thought it should be used to propagate variable values through the class to be used by the different functions, but there's clearly some flaw in my use.
Thanks for any help!
Upvotes: 2
Views: 4352
Reputation: 11075
If you don't want to always create an instance, you can make the function a classmethod
or a staticmethod
(useful if you want classes for inheritance but not specifically to hold state (local variables associated with each instance))
class TestPassingFunctions:
@staticmethod #doesn't need anything else from the class
def add_one(number):
return number + 1
@classmethod #may need to refer to the class (in this case to access cls.add_one)
def add_two(cls, number):
new_value = cls.add_one(number) + 1
return new_value
TestPassingFunctions.add_two(2) #returns 4
Here's a quick guide on the different types of methods you can use
Upvotes: 2
Reputation: 8031
You are mixing the contents of class methods, static methods and regular methods of a class.
These methods are defined to be used as regular methods, with an instance of your class:
test = TestPassingFunctions(1)
test.add_two
If you want to call them without an instance, like TestPassingFunctions.add_two(2)
, you should define them as static or class methods, with a decorator @staticmethod
and without self
as first parameter
Upvotes: 1
Reputation: 5068
You need to generate an instance of the class first:
a = TestPassingFunctions(1)
print(a.add_two(2))
Upvotes: 2
Reputation: 376
You need to initialize an object of type TestPassingFunctions
. Do this like so:
test = TestPassingFunctions(1)
test.add_two(2)
Upvotes: 5