简体   繁体   English

将函数返回的值分配给Python中的变量

[英]Assigning the value returned by a function to a variable in Python

I began coding in Python recently and encountered a problem assigning the value returned by a function to a variable. 我最近开始用Python编码,遇到一个问题,将函数返回的值赋给变量。

class Combolock:
    def _init_(self,num1,num2,num3):
        self.x = [num1,num2,num3]
    def next(self, state):
        print "Enter combination"
        combo = raw_input(">")
        if combo == self.x[state]:
            print "Correct"
            return 1
        else:
            print "Wrong"
            return 0
    def lock(self):
        currentState = 0
        while currentState < 2:
            temp = next(currentState)
            if temp == 1:
                currentState = currentState + 1
            else:
                currentState = 99
                print "ALARM"

When I call the lock function, I get an error at the line 当我调用锁定函数时,我在行处出错

temp = next(currentState)

saying that an int object is not an iterator. 说int对象不是迭代器。

You should use self.next(currentState) , as you want the next method in the class scope. 你应该使用self.next(currentState) ,因为你想要类范围中的next方法。

The function next is global and next(obj) works only if obj is an iterator . 函数next是global, next(obj)只有在obj迭代器时才有效。
You might want to have a look at the yield statement in the python documentation. 您可能希望查看python文档中的yield语句

As Andrea (+1) pointed it out you need to tell python you want to call next() method on self object, so you need to call it self.next(currentState) . 正如Andrea(+1)所指出的,你需要告诉python你想在self对象上调用next()方法,所以你需要将它self.next(currentState)

Also, note, that you have defined incorrect initializer (aka. constructor). 另请注意,您已定义了不正确的初始化程序(也称为构造函数)。 You have to use double underscores: 你必须使用双下划线:

__init__(...

instead of: 代替:

_init_(...

otherwise it is just a method - not called while object creataion. 否则它只是一种方法 - 在对象creataion时不调用。

请改用self.next(currentState),否则它指的是迭代器的next()方法,而不是你的类

The error means just what it says. 错误意味着它所说的内容。 When you use next(iterable) , next tries to call the iterable 's next method . 当你使用next(iterable)next尝试调用iterablenext 方法 However, when you do dir(0) : 但是,当你做dir(0)

['__abs__',
 # ... snip ...
 '__xor__',
 'bit_length',
 'conjugate',
 'denominator',
 'imag',
 'numerator',
 'real']

As you can see, there is no next method on an integer. 如您所见,整数上没有next方法。

If you are trying to call your own next method, then you need to use self.next not next . 如果您尝试调用自己的next方法,则需要使用self.next而不是next next is a builtin function that calls the next method of an iterator to let you do things like this: next是一个内置函数,它调用迭代器的next方法让你做这样的事情:

 for something in my_iterator:
     print something

Try: 尝试:

temp = self.next(currentState)

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

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