簡體   English   中英

我可以在Python類成員中存儲對象嗎?

[英]Can I store objects in Python class members?

我正在使用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?

你可以這樣做:

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

它按預期工作。

是。
與大多數python一樣,請嘗試一下。

創建測試對象時將實例化該對象。 即您分配給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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM