开发者

Activate method in Python

I'm trying to set my Python programs in classes. But when I have this:

class program:

    def test(v开发者_如何学Goalue):
        print value + 1

    def functionTest():
        a = test(2)

    if __name__ == "__main__":
        functionTest()

I get the error : NameError: global name 'test' is not defined

What do I have to do to 'activate' the test-method? Thanks a lot!


class Program:
    def test(self, value):
        print value + 1

    def functionTest(self):
        a = self.test(2)

if __name__ == "__main__":
    myprog = Program()
    myprog.functionTest()
  1. You have to supply self as an argument
  2. You have to call test with self.test()
  3. You have to instantiate Program (create an object out of your class)
  4. You have to call the method on that object
  5. The code to instantiate the object and call the method should not be in your class (wrong indentation)

All that above is assuming you actually want a class and use it in your code. If not, have a look at @brandizzi's answer


You do not need a class to do what you are trying to do. Actually, there is no sense on using one. Just write your code this way:

def test(value):
    print value + 1

def functionTest():
    test(2)

if __name__ == "__main__":
    functionTest()

Classes are very important and useful but I bet you are starting to learn Python yet. So take some time to look at functions, commands etc. before going to use classes :) (Also, do not forget to read the tutorial - it is indispensable)


Why are you wrapping everything in a class? It's not java. Just remove the class program line (and the indentation of everything) and it will work.


Yoou must call

 myprogram = Program()

In addition to be able to call your functions as

myprogram.funtionTest()

you must put self as a parameter in the Program methods.

This is a working example:

class Program():

    def test(self, value):
        print value + 1

    def functionTest(self):
        self.test(2)

if __name__ == "__main__":
    myprogram = Program()
    myprogram.functionTest()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜