提取物。
class Fruit:
""" An Eatables Class"""
def __init__(self, color="Black", shape="Round"): # Initailization
self.color = color # Set Class Variables to passed values
self.shape = shape # If no value passed, default to hard-coded ones.
Mango = Fruit("Raw Green", "Mangool")
# Above statement instantiates Class Fruit by passing variables as arguments.
# Thus, Mango is an **instance** of class **Fruit**
現在,在訪問變量
>>>print Mango.color
Raw Green
另一個例子
class My_List:
"""My List Implementation"""
def __init__(self, *args):
self.data = list(args)
self.Length = len(args)
def GetMean(self):
return 1.0*sum(self.data)/len(self.data)
def Add(self, *args):
self.data.extend(list(args))
self.Length += len(args)
whole_num = My_List(0,1,2,3,4,5)
# Made an **instance** of class **My_List**
變量加入
>>>print whole_num.GetMean()
2.5
>>>whole_num.Add(6, 7)
>>>print whole_num.data
[0, 1, 2, 3, 4, 5, 6, 7]
你是什麼意思'做一個實例stack'? – thefourtheye
所以基本上,我正在寫的代碼涉及一個堆棧,其中包含一個鍵和一個名稱的兩個參數。製作一個實例是否意味着初始化這兩個對象? – user2933041
'類'早上只是代碼。當你第一次調用**類來創建一個屬於這個「類」類的對象時,你會得到該類的**實例**。希望這能說明問題。 –