擅长:python、mysql、java
<p><strong>Python需要指定self。</strong>结果是,即使没有可见的完整类定义,也不会对什么是成员和什么不是成员产生任何混淆。这会导致一些有用的属性,例如:不能添加意外隐藏非成员从而破坏代码的成员。</p>
<p>一个极端的例子是:你可以编写一个类而不知道它可能有什么基类,并且总是知道你是否在访问一个成员:</p>
<pre><code>class A(some_function()):
def f(self):
self.member = 42
self.method()
</code></pre>
<p>这是完整的代码!(有些函数返回用作基的类型。)</p>
<p>另一种,类的方法是动态组合的:</p>
<pre><code>class B(object):
pass
print B()
# <__main__.B object at 0xb7e4082c>
def B_init(self):
self.answer = 42
def B_str(self):
return "<The answer is %s.>" % self.answer
# notice these functions require no knowledge of the actual class
# how hard are they to read and realize that "members" are used?
B.__init__ = B_init
B.__str__ = B_str
print B()
# <The answer is 42.>
</code></pre>
<p>记住,这两个例子都是极端的,你不会每天都看到它们,我也不建议你经常编写这样的代码,但它们确实清楚地显示了明确要求自我的各个方面。</p>