[英]Creating instances in python
我無法理解類實例是什么。 我在python中讀取了類的語法頁面。 但是,我仍然難以完全掌握實例的含義。 例如,假設我創建了一個包含兩個包含“item”和“key”的槽的類。 就我而言,我知道如何使用def __init__(self):
初始化對象def __init__(self):
使用self.key = key
和self.name = name
。 但是,我的問題涉及創建一個包含兩個參數的實例。 同樣,我如何將實例作為堆棧? 我真的不想要任何代碼,但有人可以用簡單的術語描述解決方案嗎? 多謝你們!
@drewk -
class morning(object):
__slots__ = ('key', 'name')
def __init__(self, name, key):
self.name = name
self.key = key
return self
它是實例變量和類變量之間的區別:
class Test(object):
x='CLASS x my man'
def __init__(self, x=0, y=1):
self.x=x
self.y=y
t1=Test(3,4)
t2=Test(5,6)
print 't1:', t1.x
print 't2:', t2.x
print 'class:', Test.x
打印:
t1: 3
t2: 5
class: CLASS x my man
從我的新教程中提取。
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.