简体   繁体   English

python中的无限循环

[英]Infinite loop in python

So whilst ive seen a few infinite loop codes on SO and on the web, i havent seen one the can repeatedly call a method... Here's my code.. and its not working, its just freezes.. Why? 因此,尽管我在SO和Web上看到了一些无限循环代码,但我还没有看到可以重复调用一种方法的方法。这是我的代码,它不起作用,只是冻结了。为什么?

class InfiniteLoop:

    def input():
        print("Hello")
        #num = raw_input("Enter a number: ")
        #print "You entered: ", num

    def loop():
        global input 
        #input = input()
        var = 1
        while var == 1:
            input = input() #

    loop()

Any and all help will be appreciated.. thanks ! 任何和所有帮助将不胜感激..谢谢!

EDIT: 编辑:

class Usb_Check:

def cycle(self):
    buzzer_class = Buzzer()
    lock_class = Lock()
    active = False



    device_re = "Bus \d{,3} Device \d{,3}: ID ([a-f0-9]+:[a-f0-9]+)"

    df = subprocess.check_output("lsusb", shell=True)
    for i in df.split('\n'):
        if i:
                if re.findall(device_re, i, re.I)[0] == key:
                buzzer_class.cycle(2)

I think you're a bit on the confused side about what is actually happening here. 我认为您对这里实际发生的事情有些困惑。

Have you tried pushing enter ? 您是否尝试过按Enter键 I'm guessing you haven't, or you'd get TypeError: 'str' object is not callable 我猜你还没有,或者你得到TypeError: 'str' object is not callable

Plainly, you've seen several examples of things on the internet but you haven't really understood what they're doing. 简而言之,您已经在互联网上看到了一些事例,但您并没有真正了解它们在做什么。 Allow me to comment: 请允许我发表评论:

The class declaration is not really essential to what you're trying to do here. 类声明对于您要在此处执行的操作并不是很重要。 As a matter of fact, I would probably not worry about using classes until you feel more comfortable with functions, and possibly a thing called scope. 实际上,除非您对函数感到满意,否则我可能不会担心使用类,也许还不喜欢使用范围。

class InfiniteLoop:

Here, you are not passing self in as the first argument. 在这里,您没有将self作为第一个参数传递。 You almost always see this in Python classes because that's really the whole point of using class methods (functions that are declared inside a class). 您几乎总是在Python类中看到这一点,因为这实际上就是使用类方法(在类内部声明的函数)的全部意义。

Also, input() is already the name of a function in Python - this doesn't override the existing function, though, because it's attached to your class InfiniteLoop . 另外, input()已经是Python中函数的名称-但是,它不会覆盖现有函数,因为它已附加到您的InfiniteLoop类中。 And the only way you'll ever[1] be able to call it is via InfiniteLoop.input() . 而且,您将无法调用[1]的唯一方法是通过InfiniteLoop.input()

    def input():
        print("Hello")
        #num = raw_input("Enter a number: ")
        #print "You entered: ", num

global input is why I can tell you don't understand scope. global input是为什么我可以告诉您不了解范围的原因。 This effectively does nothing. 这实际上什么也没做。 The only time you want global is if you're actually going to be assigning values and you want those changes to be visible across your application. 唯一要global是,如果您实际上是要分配值,并且希望这些更改在您的应用程序中可见。 It doesn't look like you're trying for that here. 看起来您在这里尝试的好像不一样。

    def loop():
        global input 
        #input = input()

You can actually change this piece to read while var: because 1 is "True". 您实际上可以将其更改为while var:读取while var:因为1为“ True”。 Or better yet, just go with while True: 或者更好的是, while True:

        var = 1
        while var == 1:
            input = input() #

It's certainly possible to put function calls in the body of your class, but usually you won't see this. 当然可以将函数调用放在类的主体中,但是通常您不会看到这一点。 Mainly because it's not terribly clear what you are trying to do when that happens. 主要是因为这种情况发生时您并不确定要做什么。 My guess is you just put it here because that was the only way you could get your code to run. 我的猜测是您只是将其放在此处,因为那是使代码运行的唯一方法。

    loop()

If you were trying to write this class-style, then you probably want to write it like so: 如果您尝试编写这种类样式,则可能需要这样编写:

class InfiniteLoop:
    def __init__(self):
        self.loop()

    def input(self):
        print("No input here!")

    def loop(self):
        while True:
            self.input()

InfiniteLoop()

Or, better yet you could just write it without the class: 或者,更好的是,您可以不用类就可以编写它:

def my_input(): # not input, to avoid shadowing the input() function
    print("Nope, still no input")


def loop():
    while True:
        my_input() # No global necessary, you can see the function from here!

[1]:Not really, but to do anything else is probably just for fun and learning. [1]:不是真的,但是做其他事情可能只是为了娱乐和学习。

class InfiniteLoop():
    def input(self):
        print "Hello"

    def loop(self):
            var =1
            while var == 1:
                self.input()


if __name__ == "__main__":
    A = InfiniteLoop()
    A.loop()

I realize you're new at this, but there are a number of helpful tutorials on the internet for free. 我知道您是新手,但是互联网上有许多免费的有用教程。 You may want to read through them prior to posting on SO. 您可能需要先通读它们,然后再发布在SO上。 Hope the above code helps you get started. 希望以上代码能帮助您入门。

What's happening 发生了什么

It is not your program that freezes, it is the Python interpreter parser which gets stuck while reading the last line of your program. 冻结的不是您的程序,而是在读取程序的最后一行时卡住的Python解释器解析器。 If you press the Enter key a few times, it gets unstuck and prints this 如果按几次Enter键,它会解开并打印出来

Traceback (most recent call last):
  File "infiniteloop.py", line 1, in <module>
    class InfiniteLoop:
  File "infiniteloop.py", line 15, in InfiniteLoop
    loop()
  File "infiniteloop.py", line 13, in loop
    input = input() #
  File "<string>", line 0

I am no language lawyer so I cannot tell you what is actually happening there. 我不是语言律师,所以我无法告诉您那里实际发生了什么。 In a class definition you do have the def function_name(self, param1, param2, ...): construct or that preceeded by an annotation. 在类定义中,您确实具有def function_name(self, param1, param2, ...):构造或以注释开头的构造。 I do not have a slightest idea what happens if you try to call a function/method there. 我完全不知道如果您尝试在那里调用函数/方法会发生什么。

What I do know is that judging by what you've probably tried to accomplish you have the syntax wrong. 我所知道的是,从您可能尝试完成的判断来看,语法有误。

Syntactically correct version 语法正确的版本

You have the indentation wrong on your last line. 最后一行上的缩进错误。 It should not be indented, it is not a part of that class, it should be on the same level as the class declaration. 它不应缩进,它不是该类的一部分,它应该与类声明处于同一级别。

A syntactically correct version of your program would be this 您的程序在语法上正确的版本是:

class InfiniteLoop:
    def input():
        print("Hello")
        #num = raw_input("Enter a number: ")
        #print "You entered: ", num

    def loop():
        global input 
        #input = input()
        var = 1
        while var == 1:
            input = input() #

loop()

Of course, that would not run because there is not a top level function named loop anywhere. 当然,这不会运行,因为任何地方都没有名为loop的顶级函数。 But syntax is now right. 但是语法现在是正确的。

The error looks like this 错误看起来像这样

Traceback (most recent call last):
  File "syntax", line 14, in <module>
    loop()
NameError: name 'loop' is not defined

and as to how to fix it you can refer to one of the other answers. 关于如何解决它,您可以参考其他答案之一。 Most importantly of all, methods in Python do get their this object (actually self object, as it is customary to call it in Python) explicitly as their first parameter. 最重要的是,在Python方法都得到他们的this对象(实际上是self的对象,因为它是习惯性地调用它在Python)明确作为其第一个参数。 So you have to declare the methods with def method_name(self, some, other, params): . 因此,您必须使用def method_name(self, some, other, params):声明方法。

What would I do 我该怎么办

Keep it simple. 把事情简单化。 Do not declare a class when what you mean is just a couple of functions. 当您的意思只是几个函数时,请勿声明类。 And just to make sure, you no not have to declare a class in a Python program. 只是为了确保您不必在Python程序中声明一个类。

def get_user_input():
    print("Hello")
    num = raw_input("Write something and press Enter: ")
    return num

def main():
    while True:
        input = get_user_input()
        print "You entered: ", input

if __name__ == '__main__':
    main()

The if __name__ construct is a useful way how to run something if the file is directly executed, but not to run the code if the file is included from some other place. if __name__直接执行文件,则if __name__构造是一种有用的方法,但是如果文件是从其他位置包含的,则该方法不能运行代码。

In conclusion 结论

Read this SO question, answers, and the free to read Dive into Python book that is recommended there Learning Python coming from PHP ;) 阅读这个SO问题,答案和免费阅读《 Dive into Python》一书,在那本书推荐使用《 学习来自PHP的Python》 ;)

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

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