摘自我的新手教程。
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]