【问题标题】:How to properly create class global variable [duplicate]如何正确创建类全局变量[重复]
【发布时间】:2017-05-31 20:29:19
【问题描述】:

为什么以下计数器不起作用,以及如何修复它:

class Test():
   def __init__(self):
       self.counter = 0

   def increment(self):
       print counter++

谢谢。

【问题讨论】:

  • 当你说不起作用时,究竟是什么问题?有例外吗?是否运行不正常。在这种情况下,您的问题似乎很明显,但是如果您不希望“关闭者”解决您的问题,最好对问题进行一些描述。
  • 顺便说一句,counter 的目的是什么?正如我认为你可能需要它作为类变量而不是实例变量(因为类中计数器的一般用法是计算类的对象数)

标签: python


【解决方案1】:

你可以使用__init__

class C:
    counter = 0
    def __init__(self):
        C.counter += 1

class C:
    counter = 0
    @classmethod
    def __init__(cls):
        cls.counter += 1

或使用其他方法,如

class C:
    counter = 0

    @classmethod
    def my_function(cls):
        cls.counter += 1

【讨论】:

    【解决方案2】:

    要在类中使用变量,请在其前面加上self

    class MyCounter():
       def __init__(self, number):
           self.counter = number
    
       def increment(self):
           self.counter += 1
           print(self.counter)
    
    [IN] >>> counter = MyCounter(5)
    [IN] >>> print(counter.increment())
    [OUT] >>> 6
    

    【讨论】:

    • ++ 仍然不是有效的python...(尽管我不是你的反对票)
    • 我改了,哎呀。
    • 我的分数刚刚从-1翻到1-1,哈哈
    【解决方案3】:

    ++ 不是有效的 python

    你需要self.counter += 1

    【讨论】:

      猜你喜欢
      • 2015-01-20
      • 2013-01-04
      • 2014-11-29
      • 2014-01-12
      • 1970-01-01
      • 1970-01-01
      • 2015-08-19
      • 2016-10-25
      • 1970-01-01
      相关资源
      最近更新 更多