Reputation: 33
I am trying to call method within a class; that call is the last line below, self.z()
class Wait:
def __init__(self,a):
self.a = a
def countdown(self,a):
for remaining in range(self.a, 0, -1):
sys.stdout.write("\r")
sys.stdout.write("{:2d} seconds remaining.".format(remaining))
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("\rWait Complete! \n")
def z(self):
self.countdown(100)
self.z()
However, I get this error:
Traceback (most recent call last):
File "./countdown.py", line 6, in <module>
class Wait:
File "./countdown.py", line 18, in Wait
self.z()
NameError: name 'self' is not defined
How can I call countdown
from another method within this class ?
Upvotes: 0
Views: 2237
Reputation: 77847
The problem is that self is not defined in the class body; self is a parameter of each of the methods, but you're not inside any method at that point. I think you might be trying to test this with a 100-second countdown, which means that you need that bottom code in your main program:
class Wait:
def __init__(self,a):
self.a = a
def countdown(self,a):
for remaining in range(self.a, 0, -1):
sys.stdout.write("\r")
sys.stdout.write("{0:2d} seconds remaining.".format(remaining))
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("\rWait Complete! \n")
def z(self):
self.countdown(100)
ticker = Wait(10)
ticker.z()
Note that your code ignores the 100 value sent in from z, instead using the timer value set at creation. Also note that I've corrected your formatted output statement.
Can you take it from here?
Upvotes: 2