Python main call within class

后端 未结 3 1607
盖世英雄少女心
盖世英雄少女心 2021-02-01 16:38

I haven\'t done much python - coming from a C/Java background - so excuse me for asking such a simple question. I am using Pydev in Eclipse to write this simple program, and all

相关标签:
3条回答
  • 2021-02-01 17:06

    Well, first, you need to actually define a function before you can run it (and it doesn't need to be called main). For instance:

    class Example(object):
        def run(self):
            print "Hello, world!"
    
    if __name__ == '__main__':
        Example().run()
    

    You don't need to use a class, though - if all you want to do is run some code, just put it inside a function and call the function, or just put it in the if block:

    def main():
        print "Hello, world!"
    
    if __name__ == '__main__':
        main()
    

    or

    if __name__ == '__main__':
        print "Hello, world!"
    
    0 讨论(0)
  • 2021-02-01 17:08

    Remember, you are NOT allowed to do this.

    class foo():
        def print_hello(self):
            print("Hello")       # This next line will produce an ERROR!
        self.print_hello()       # <---- it calls a class function, inside a class,
                                 # but outside a class function. Not allowed.
    

    You must call a class function from either outside the class, or from within a function in that class.

    0 讨论(0)
  • 2021-02-01 17:15

    That entire block is misplaced.

    class Example(object):
        def main(self):     
            print "Hello World!"
    
    if __name__ == '__main__':
        Example().main()
    

    But you really shouldn't be using a class just to run your main code.

    0 讨论(0)
提交回复
热议问题