在其中,我发现了大量使用关键字self,我发现我总是忘记输入。例如,而不是self.rect.centerx
我会打字rect.centerx
因为对我来说直角已经是类的成员变量。
在这种情况下,我可以想到的Java并行是必须在所有对成员变量的引用前加上self前缀。
我是否在所有成员变量前加上self?
Python需要指定Self。您可以编写一个类,而不知道它可能有哪些基类,并且始终知道您是否正在访问一个成员:
class A(some_function()):
def f(self):
self.member = 42
self.method()
那是完全密码!(一些)_函数返回用作基的类型。)
Another, where the methods of a class are dynamically composed:
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.>
请记住,这两个例子都是极端的,您不会每天都看到它们,我也不建议您经常编写这样的代码,但它们确实清楚地显示了自我被明确要求的方面。