Python 缺少初始化的类变量

Python 缺少初始化的类变量,python,Python,我编写了一些代码,在给定任意数量n的情况下,找到要计数到1的最小事件数 class Solution(object): def __init__(self): events=0 def integerReplacement(self, n): """ :type n: int :rtype: int """ if n==1 or not n: return se

我编写了一些代码,在给定任意数量n的情况下,找到要计数到1的最小事件数

class Solution(object):
    def __init__(self):
        events=0
    def integerReplacement(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n==1 or not n:
            return self.events
        if n%2==0:
            self.events=self.events+1
            self.integerReplacement(self,n/2)
        else:
            self.events=self.events+1
            self.integerReplacement(self,(n-1)/2)
        return self.events

def stringToInt(input):
    return int(input)

def intToString(input):
    if input is None:
        input = 0
    return str(input)

def main():
    import sys
    def readlines():
        for line in sys.stdin:
            yield line.strip('\n')
    lines = readlines()
    while True:
        try:
            line = lines.next()
            n = stringToInt(line)



                ret = Solution().integerReplacement(n)

                out = intToString(ret)
                print out
            except StopIteration:
                break

    if __name__ == '__main__':
        main()
我得到的错误是

Finished in N/A
AttributeError: 'Solution' object has no attribute 'events'
Line 12 in integerReplacement (Solution.py)
Line 38 in main (Solution.py)
Line 46 in <module> (Solution.py)
已完成,不适用
AttributeError:“解决方案”对象没有属性“事件”
整数置换(Solution.py)中的第12行
干管中的第38行(Solution.py)
第46行in(Solution.py)

我不知道为什么它不能识别我在init函数中声明的events变量。我做错了什么?

它需要是实例变量的属性
self
,因此更改:

        events=0
致:


它需要是实例变量
self
的一个属性,因此更改:

        events=0
致:


正如Cireo所评论的,您需要使用:

self.events = 0
self告诉python声明的变量必须可供整个类访问。否则,它只能在_init__函数的局部范围内访问。换句话说,event和self.event将是两个独立的变量

或者,如果出于任何原因希望使用events=0,您希望将其作为类属性,那么您当前的代码将正常工作。为此,请删除uuu init_uuuu函数并声明变量:

class Solution(object):
    event = 0

    # The rest of your code

正如Cireo所评论的,您需要使用:

self.events = 0
self告诉python声明的变量必须可供整个类访问。否则,它只能在_init__函数的局部范围内访问。换句话说,event和self.event将是两个独立的变量

或者,如果出于任何原因希望使用events=0,您希望将其作为类属性,那么您当前的代码将正常工作。为此,请删除uuu init_uuuu函数并声明变量:

class Solution(object):
    event = 0

    # The rest of your code

events=0
不做任何事情,您需要将其设置为
self.events=0
events=0
不做任何事情,您需要将其设置为
self.events=0