【问题标题】:How to access and modify global variables in python class如何访问和修改python类中的全局变量
【发布时间】:2022-01-09 08:38:37
【问题描述】:

我是 Python 类的新手。我试图编写一个链表程序,我需要一个全局变量来计算节点数而不是函数。 所以,当我这样做时:

class DoublyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        self.count = 0

然后在链表类之外我无法访问这个 self.count(在我创建这个类的对象的部分等)我认为因为它是这个类的一个局部变量我得到了错误. 所以,我尝试了这个:

count = 0
class DoublyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        global count
        self.count=0

我在想,如果我把全局变量作为这个类的数据字段,那么我就不需要写了:

global count

在这个类下的每个函数中。 但是每当我访问计数时,它的值为零。 有人可以帮忙吗?

编辑:显示功能不需要这个计数,所以我可以看到我的列表被完美地创建了。我只想在类外使用 count 访问节点数,以便在调用插入或删除函数等之前检查位置有效性。 如果有帮助,我会将 sn-p 附加到它给我错误的位置:

pos = int(input("Enter the position : \n"))
if (pos>(count+1))or(pos<1):
    print("Invalid Position")

【问题讨论】:

    标签: python python-3.x class oop


    【解决方案1】:

    不需要在类中创建一个全局变量,而是可以创建一个self.[variable name],但是要更改变量值,你可以self.[var name] = [new value] 例如:

    class myclass:
        def __init__(self):
            self.counter = 1
    
    classvar = myclass();
    print(classvar.counter)
    

    【讨论】:

    • 非常感谢@Elhadede,它完全解决了我的问题。
    【解决方案2】:

    我认为您误解了关键字global 的含义。 global 用于访问/修改在普通脚本中定义的变量,而不是在函数中,例如

    #test.py
    c = 1
    
    def test1():
        c = 3 #this will not modify the c which we declared earlier
    
    test1()
    print(c) #will print 1
    
    def test2():
         global c #this tells the interpreter to look for the previously defined c
         c = 3
    test2()
    print(c) #will print 3
    
    

    现在要访问对象的成员,您只需要使用objectname.variablename

    【讨论】:

      【解决方案3】:

      在类中使用 global 是不常见的。要访问您的类属性,您只需实例化一个新对象。

      class Car:
          def __init__(self):
          self.color = 'red'
          self.number_of_door = 5
      
      # let's say I want to get the number of doors and plus one for Toyota
      
      Toyota = Car()
      print(Toyota.number_of_door + 1)
      
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-20
        • 2012-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-22
        相关资源
        最近更新 更多