在python中创建实例

时间:2013-11-05 03:37:29

标签: python class instance

我无法理解类实例是什么。我在python中读取了类的语法页面。但是,我仍然难以完全掌握实例的含义。例如,假设我创建了一个包含两个插槽的类,其中包含" item"和一个"键"。就我而言,我知道如何使用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

2 个答案:

答案 0 :(得分:2)

它是实例变量和类变量之间的区别:

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

答案 1 :(得分:0)

从我的新教程中摘录。

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]