Reputation: 332
I am trying to implement a sample python program with class , some method and instance creation (object creation) with main method . But I am new to python I tried with lot of example but I am not getting the exact flow of the above in python . Below is the java code i need the equivalent in python .
Class hello { //Class name
void display () { // user defined method
System.out.println("Hello");
}
public static void main(String args[]) { //main method
hello obj=new hello(); //instance creation (object creation)
obj.display(); // invoking methods
}
}
Output
Hello
I need the above code in python please help me out in this
The python what I tried with the same
import sys
class MyApplication():
def get_name():
print 'hi'
def main():
app=MyApplication()
print('Hi ' + app.get_name())
if __name__ == '__main__':
main()
But this above python code is not working and not giving any error and output .I am getting blank console
Upvotes: 1
Views: 1087
Reputation: 4490
In python, intendation is very important. If you intend some code segment, it means that code segment is part of a block.
See following snippet from your code
def main():
app=MyApplication()
print('Hi ' + app.get_name())
if __name__ == '__main__':
main()
You should correct indentation of this code segment. It should be,
def main():
app = MyApplication()
print('Hi ' + app.get_name())
if __name__ == '__main__':
main()
'__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.
A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported: A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported: - Python documentation
Upvotes: 7
Reputation: 332
Thanks for your replay after doing the modification it is working and also added "self" inside my method get_name(self)
as args it is working now
Code Below
import sys
class MyApplication():
def get_name(self):
print 'hi'
def main():
app=MyApplication()
app.get_name()
if __name__ == '__main__':
main()
Upvotes: 1