0

我正在使用 Pygame2 多媒体库用 Python 编写游戏,但我更习惯于使用 ActionScript 3 开发游戏。在 AS3 中,我认为不可能将对象存储在静态变量中,因为静态变量在对象可以被实例化之前被初始化。

但是,在 Python 中,我不确定这是否成立。我可以将对象实例存储在 Python 类变量中吗?什么时候实例化?每个类或每个实例都会实例化一个吗?

class Test:
    counter = Counter() # A class variable counts its instantiations
    def __init__(self):
        counter.count() # A method that prints the number of instances of Counter

test1 = Test() # Prints 1
test2 = Test() # Prints 1? 2?
4

2 回答 2

3

你可以这样做:

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

它按预期工作。

于 2009-08-17T22:28:30.987 回答
3

是的。
与大多数 python 一样,试试看。

它将在创建 Test 对象时实例化。即您分配给 test1
的计数器对象是按类创建的

运行以下命令查看(访问类变量需要self

class Counter:
  def __init__(self):
    self.c = 0

  def count(self):
    self.c += 1
    print 'in count() value is ' , self.c
    return self.c

class Test:
  counter = Counter() # A class variable counts its instantiations 
  print 'in class Test'
  def __init__(self):
    print 'in Testinit'
    self.counter.count() # A method that prints the number of instances of Counter

test1 = Test() # Prints 1
test2 = Test()
于 2009-08-17T22:43:36.950 回答