简体   繁体   English

从主python调用函数

[英]Calling functions from main python

I have some python 3.4 code that works fine: 我有一些python 3.4代码可以正常工作:

def run():
    m = 0
    while m != 1:    
        p = input('Please choose p: ')
        p = makeInt(p)
        #Some other code
        print(p)
        m = makeInt(input('Enter 1 if you would like to quit: '))

def makeInt(i):
    try:
        i = int(i)
    except ValueError:
        i = input('Incorrect input! Enter your answer: ')
        i = makeInt(i)
    return i

#Some other functions    

if __name__ == '__main__':
    run()

I want to put all this code in a class (Except possibly if __name__ == ...) When I put all the code including if __name__ == ... in a class like so: 我想将所有这些代码放在一个类中(除非可能if __name__ == ...)当我把所有代码包括if __name__ == ...放在类这样的类中时:

class Foo(object):
    def run(self):
        m = 0
        while m != 1:    
            p1 = input('Please choose p: ')
            p1 = self.makeInt(p1)
            #Some other code
            print(p1)
            m = self.makeInt(input('Enter 1 if you would like to quit: '))

    def makeInt(self, i):
        try:
            i = int(i)
        except ValueError:
            i = input('Incorrect input! Enter your answer: ')
            i = self.makeInt(i)
        return i
    #Some other functions and stuff

    if __name__ == '__main__':
        run()

I get the following error: TypeError: run() missing 1 required positional argument: 'self' . 我收到以下错误: TypeError: run() missing 1 required positional argument: 'self' When I remove the self argument from run() it runs until makeInt() is called and then I get: NameError: name 'makeInt' is not defined . 当我从run()删除self参数时,它会一直运行,直到makeInt()然后我得到: NameError: name 'makeInt' is not defined I get the same error if I take the if statement out of the class and call Foo.run() . 如果我从类中取出if语句并调用Foo.run()我会得到同样的错误。 I have some other code earlier in this program that works when I call functions of a class from another function in that same class. 我在这个程序的前面有一些其他代码,当我从同一个类中的另一个函数调用类的函数时,它可以工作。 I realize I don't have to put all my code in a class, but in this case I want to. 我意识到我不必将所有代码放在一个类中,但在这种情况下我想要。 Why am I getting these errors and what can I do to put my working code in a class? 为什么我会收到这些错误,我该怎么做才能将我的工作代码放在一个类中?

As others mentioned, by putting your functions in a class, you've made them methods, that means they need an instance of this class as first argument. 正如其他人所提到的,通过将您的函数放在一个类中,您已经使它们成为方法,这意味着它们需要此类的实例作为第一个参数。 So you can indeed call your run method using Foo().run() as Foo() will create an instance of Foo . 所以你确实可以使用Foo().run()调用你的run方法,因为Foo()会创建一个Foo实例。

Another way (eg if you don't need the class for anything else than encapsulation) is to make them static , using the staticmethod decorator: 另一种方法(例如,如果你不需要除了封装以外的任何其他类)是使用staticmethod装饰器使它们静态

class Foo(object):
    @staticmethod
    def run():
        ...

    @staticmethod
    def makeInt(i):
        ...

if __name__ == '__main__':
    Foo.run() # don't need an instance as run is static

In Python, a method can be static, ie no need for any special argument, a class method, ie first argument is the class itself, or a standard method, ie the first argument is an instance of the class. 在Python中,方法可以是静态的,即不需要任何特殊参数,类方法,即第一个参数是类本身,或者是标准方法,即第一个参数是类的实例。

Since you wrap your code within a class, your run() is a method now. 由于您将代码包装在一个类中,因此run()现在是一种方法。 You should remove your main from your class by unindenting it and initialize an instance of your class: 你应该通过unindenting从你的类中删除你的main并初始化你的类的实例:

if __name__ == '__main__':
    Foo().run()

It thinks the guard is a part of your class due to the indentation: you have your guard indented to the same level as the other class members. 由于缩进,它认为警卫是你班级的一部分:你的警卫缩进到与其他班级成员相同的水平。 Unindent the Unindent the

if __name__ == '__main__'

Also change it to be 也改变它

if __name__ == '__main__':
  main()

and then instantiate a new object of type Foo in your newly created main() function 然后在新创建的main()函数中实例化一个Foo类型的新对象

def main():
  newFoo = Foo()
  newFoo.run()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM