class classA:
#saved as classA.py    
   def __init__(self):
      print "class A"
      printB()
   
   def printB():
         print "B"
>>> classA()
class A
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    classA()
  File "C:\Documents and Settings\Owner\Desktop\timetable\classA.py", line 5, in __init__
    printB()
NameError: global name 'printB' is not defined

Using the class above, I get the error saying that printB is not defined. It works when printB() is moved outside of the class. I want to have printB to be part of the class, like a static method. I tried adding "@staticmethod" above the 'def printB()' but that doesn't seem to work. Am I missing something?

Recommended Answers

printB is not part of the class unless you define as being a class member, like so

def printB(self):
         print "B"

You then call it with
self.printB()
See this page from "How To Think Like A Computer Scientist" http://www.greenteapress.com/thinkpython/html/book018.html

Jump to Post

No, in python methods, there is no implicit argument (like C++'s this for example)

Jump to Post

All 5 Replies

Thanks for the link, I'm looking at it now.

class classA:
#saved as classA.py    
   def __init__(self):
      print "class A"
      classA.printB()
      
   @staticmethod
   def printB():
      print "B"

classA()

printB() does not rely on the instance, it would be better as a static method. This code works, but I need to do 'classA.' first. Is there any way to omit calling the class since the method is already in the class?

No, in python methods, there is no implicit argument (like C++'s this for example)

Oh, I'll just add 'self' to the method then.

Thanks for the fast reply.

Traceback (most recent call last):
File
Traceback (most recent call last):
File "C:/Users/Web/Desktop/velocity.py", line 9, in <module>
main()
File "C:/Users/Web/Desktop/velocity.py", line 2, in main
angle, vel, h0, tiime = getInputs()
NameError: global name 'getInputs' is not defined

Note: Please post your own new thread and show the code that causes the error.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.