简体   繁体   English

Python:类函数中的全局变量

[英]Python: Global variable in class function

class LinkedList():
    
    def __init__(self):
        self.head = None
    
    def loopCheck(self):
        global fast
        slow = self.head
        fast = self.head 
        while(fast.next!=None):
            slow = slow.next
            fast = fast.next.next
            if slow.data == fast.data:
                return True
            
        return False
    def lenLoop(self):
        if not(self.loopCheck):
            print("No loop found")
        else:
            print(fast.data)

The variable fast is not getting recognised in the lenLoop() function.在 lenLoop() 函数中无法识别变量fast How do I make a variable global inside a class?如何在类中使变量成为全局变量?

You can declare it in the constructor of your class as self.fast as you have done with self.head .您可以在类的构造函数中将其声明为self.fast就像使用self.head所做的self.head Intuitively speaking, self is like a dictionary which stores the values of the variables along with their names so that they can be accessed anywhere within the class.直观地说,self 就像一个字典,它存储变量的值及其名称,以便可以在类中的任何地方访问它们。

Because you are not calling your function.因为你没有调用你的函数。 Try self.loopCheck() instead of self.loopCheck .尝试self.loopCheck()而不是self.loopCheck

def lenLoop(self):
    if not(self.loopCheck()):
        print("No loop found")
    else:
        print(fast.data)

Output输出

1 -> 2 -> 3 -> None
No loop found

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

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