我在理解什么是类实例时遇到了麻烦。我在语法页上阅读了python中的类。但是,我仍然很难完全掌握实例的含义。例如,假设我创建了一个类,该类具有两个包含“项目”和“键”的插槽。就我而言,我知道如何使用def __init__(self):
withself.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
从我的newb教程中摘录。
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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句