<pre><code>def thisIsAFunction(inputNumber):
oneMore= inputNumber+ 1
return oneMore
</code></pre>
<p>这是一个函数,它返回比输入数字多1个的值。在</p>
<p>所以在以后的代码中你会这样称呼它</p>
^{pr2}$
<p>然后当您想:<code>print anotherVariable</code>时,它将打印<code>6</code></p>
<p>类是相似的,但更广泛和更具包容性</p>
<pre><code>class thisIsaClass:
someVar = 1
def __init__(self, inputNumber):
self.inputNumber = inputNumber
</code></pre>
<p>这只是定义了一个名为“thisIsaClass”的对象。。。。创建对象。。。。在</p>
<pre><code>>>> a = thisIsaClass(1) #creating one 'thisisaclass' object called a
>>> b = thisIsaClass(2) #another called b
>>>
>>> a.inputNumber # getting inputnumber from a
1
>>> b.inputNumber
2
>>> a.someVar #someVar doesnt have 'self' in front of it so its not referring to its own someVar, its referring to its classes someVar
1
>>> b.someVar
1
>>> thisIsaClass.someVar = 3
>>> a.someVar #see? it changed it for all of th someVars
3
>>> b.someVar #because its the same someVar
3
>>> thisIsaClass.inputNumber #and THIS one doesnt actually have a "inputNumber" because it only belongs to the actual objects
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class thisIsaClass has no attribute 'inputNumber'
</code></pre>
<p>如果这让人困惑,那么看待一个类的最好方法就是将它与人联系起来。在</p>
<pre><code>class human:
def __init__(self, name, height, age):
self.name = name
self.height = height
self.age = age
beth = human('beth','64 inches', 19)
beth.age
19
</code></pre>
<p><code>__init__</code>是一个方法,因为它是类中的一个定义。(老实说,我不知道为什么叫这个。。。如果我们要在init-like下面定义另一个函数(但是它在一个类中,所以它是一个方法lol)</p>
<pre><code> def birthday(self):
self.age = self.age+1
</code></pre>
<p>每次我们想给贝丝过生日,我们都会打字</p>
<pre><code>beth.birthday()
beth.age
20
</code></pre>