Reputation: 691
I'm a newbie to PyDev in Eclipse. When coding simple programs, I use print() statements regularly in order to track the values of variables. I want these values to be printed to the console but I couldn't get any value printed in the console so far.
Here's a simple piece of code to demonstrate what I'm trying to do.
class MyClass(object):
def __init__(self):
myClassObject= MyClass()
myClassObject.greet()
def greet(self):
print("stackoverflow is the best !!!")
I'm expecting to see the string "stackoverflow is the best !!!" in the console but when I run the code I get nothing at all. What am I supposed to do?
Thanks in advance
Upvotes: 2
Views: 7790
Reputation: 691
I just learnt that my code portion in the question was meaningless because I have instantiated the objects in __init__(self)
. So the object has to be created inside a if __name__ == '__main__':
instead.
I have written a complete module to demonstrate this. (Observe there are multiple classes in Classes.py module and then it is imported in the second part of the code)
'''
Classes.py
'''
class MyClass(object):
def greet(self):
print("Hello World")
class MyNextClass(object):
def greetAgain(self):
print("Hello again")
'''
MyMain.py
'''
import Classes
if __name__ == '__main__':
a=Classes.MyClass()
a.greet()
b=Classes.MyNextClass();
b.greetAgain()
The above code makes sense and it will output to the console without problems.
Upvotes: 0
Reputation: 11531
You have not instantiated the class. In order to produce output from what you've got try the following:
if __name__ == '__main__':
instance = MyClass()
-- REVISED --
In light of your rewritten code, you should have the following:
class MyClass(object):
def __init__(self):
#myClassObject= MyClass() # Causes recursion error.
#myClassObject.greet() # You should not be accessing your instance method this way
self.greet()
def greet(self):
print("stackoverflow is the best !!!")
if __name__ == '__main__':
instance = MyClass()
Your example appears to be overly complicated. You would do well to review class usage in Python for Python 2.7 or Python 3.3.
Upvotes: 2
Reputation: 4711
__init__
is called when the class is instantiated (cf. this question). Adding my_instance = MyClass()
at the end of your snippet will create an instance of the MyClass
class and should print out what you want:
class MyClass(object):
def __init__(self):
print("stackoverflow is the best !!!")
my_instance = MyClass()
Upvotes: 0