<p>假设你有一个闪亮的Foo类。
你有三个选择:</p>
<p>1)要在类的定义中使用类的方法(或属性):</p>
<pre><code>class Foo(object):
attribute1 = 1 # class attribute (those don't use 'self' in declaration)
def __init__(self):
self.attribute2 = 2 # instance attribute (those are accessible via first
# parameter of the method, usually called 'self'
# which will contain nothing but the instance itself)
def set_attribute3(self, value):
self.attribute3 = value
def sum_1and2(self):
return self.attribute1 + self.attribute2
</code></pre>
<p>2)要使用类定义之外的类的方法(或属性)</p>
<pre><code>def get_legendary_attribute1():
return Foo.attribute1
def get_legendary_attribute2():
return Foo.attribute2
def get_legendary_attribute1_from(cls):
return cls.attribute1
get_legendary_attribute1() # >>> 1
get_legendary_attribute2() # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo) # >>> 1
</code></pre>
<p>3)要使用实例化类的方法(或属性):</p>
<pre><code>f = Foo()
f.attribute1 # >>> 1
f.attribute2 # >>> 2
f.attribute3 # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3 # >>> 3
</code></pre>