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 ?
1 Answer 1
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?
self.z()immediately upon object creation?self.z()that works only from within an instance method of the class. what do you want to achieve?countdownas a standalone function?self.countdown(some_number), exactly as you have done. There's nothing wrong withcountdownin your code; the problem is that you're callingz()in a place where you're not allowed to. Presumably in your real code, this won't be a problem.