matt2605 matt2605 - 8 months ago 86
Python Question

How to use self in python

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:

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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download