Reputation: 216
I'm new to programming and I want someone to explain using 'self' in python in the following context.
class Box:
def __init__(self):
self.length = 1.0
self.width = 1.0
self.height = 1.0
def set_dimensions(self, newL, newW, newH):
self.length = newL
self.width = newW
self.height = newH
def volume(self):
return (self.length * self.width * self.height)
box = Box:
box.set_dimensions(2.0,3.0,4.0)
print(box.volume())
This code causes an exception:
Error: box.set_dimensions(2.0,3.0,4.0) needs exactly 4 arguments, 3 given
Can someone explain how to use 'self' when calling methods please?
Upvotes: 1
Views: 532
Reputation: 3949
If you write box = Box
, you make box
a variable referring to a class Box
. It's very rare that you would need a variable to refer to a class. When calling method of a class, you need to supply an instance of that class as the first argument, but you haven't created any such instance.
Instead, write box = Box()
- that would create and instance of the class Box
. And then the remainder of the code would be valid. When calling a class method on a class instance, the instance is passed as an additional first argument, the one that is named self
in the method definition.
Upvotes: 2
Reputation: 164
To add something to the answer, you can try to understand self
in class function variables as something that when it is encoutnered python internally converts the objects method into calling it from the class, so when you are calling
SomeBoxObject.setDimensions(someLen, otherLen, evenOtherLen)
Python turns this into
Box.setDimensions(SomeBoxObject, someLen, otherLen, evenOtherLen)
Upvotes: 0
Reputation: 52181
Use parenthesis to create an instance of your class
box = Box() # Use parenthesis here not :
box.set_dimensions(2.0,3.0,4.0) # Now no error
print(box.volume()) # Prints 24.0
Upvotes: 1