<p>我觉得几周前我和你在同一条船上,虽然他们仍然很动摇,但我会尽力向你解释自我和自我。请温柔点,其他评论者!;)</p>
<p>我要先解释一下“自我”,因为它可能会使init更清楚。当我想上课时,我可以:</p>
<pre><code>class Car:
# I can set attributes here ( maybe I want all my cars to have a:
size = 0
# well eventually my car object is going to need to do stuff, so I need methods -
# methods are like functions but they are only usable by the class that encompasses them!
# I create them the same way, just inside the indentation of the class, using def func():
def drive(self):
print "vroom"
# pretend this is the function that I would call to make the car drive.
</code></pre>
<p>好吧。我们有一些事情要谈的只是这个布局。我们已经确定了汽车应该做什么,但我们还没有做任何事情。(我保证这一切都是相关的!)
为了创建car的实例(一次出现),我们可以将car对象赋给一个新变量:</p>
^{pr2}$
<p>现在我可以使用我们在car类中定义的所有方法,比如drive!
我们可以通过键入以下内容来调用该函数:</p>
<pre><code>myCar.drive()
</code></pre>
<p>这会打印“vroom”
我可以在同一个程序中创建car()类的第二个实例(尽管它是一个完全不同的对象),方法是:</p>
<pre><code>newCar = car()
</code></pre>
<p>现在,《盗梦空间》开始了。。。我做了一个非常简单的课程,课程变得非常庞大和可怕,几乎不可能在一个晚上就全部理解,但我现在要向你解释一下自我。在</p>
<p>“myCar”是我用来保存我创建的car对象的变量,如果我有其他方法需要引用该对象,它就变成了“self”参数。
本质上,我的车.vroom()就是说自我.vroom(),如果我需要在类的另一个方法中引用.vroom()。在</p>
<p>总而言之,我们有这样的东西:</p>
<pre><code>class Car:
size = 0 # a global attribute for all car objects
def drive(self): #self is the argument!
print "vroom!"
myCar = car() # we've initialized the class but havent used it here yet!
myCar.drive() # this prints "vroom"
</code></pre>
<p>另一种解释方法是,就像在普通函数中一样,self只是调用函数的对象的占位符。在</p>
<p>现在,如果有意义的话太棒了,否则我会再编辑一次。
def<strong>init</strong>(self):使用相同的理论,从类中获取一个对象,并在类每次创建对象时向它提供指令。在</p>
<pre><code>class car:
def __init__(self): # needs self, to refer to itself, right?
self.name = name # now we can assign unique variables to each INSTANCE of the car class.
</code></pre>
<p>你可以使用def<strong>init</strong>并用它做一些疯狂的事情,比如在里面你可以立即调用其他方法和东西。基本上,就像说“嘿,物体!你还活着,去检查一下<strong>init</strong>函数里面有什么,你需要所有这些东西!快走!在</p>
<p>告诉我这是否有帮助,或者我能说得更清楚些。就像我说的,我只是把我的头都裹在这上面,所以也许我的解释需要一些工作。干杯:)</p>