作为地球上最糟糕的OOP程序员之一,我一直在阅读许多示例代码,以帮助“了解”类的用途.最近我发现了这个例子:
class NextClass: # define class
def printer(self, text): # define method
self.message = text # change instance
print self.message # access instance
x = NextClass() # make instance
x.printer('instance call') # call its method
print x.message # instance changed
NextClass.printer(x, 'class call') # direct class call
print x.message # instance changed again
看起来直接类调用与实例调用之间没有区别.但这却与Zen背道而驰,因为它包含了类似的功能,但对它们没有任何用处.那么,如果有区别,那是什么?性能?减少开销?也许可读性?
解决方法:
没有区别. instance.method(…)是class.method(instance,…).但这并没有违背禅宗,因为它说(强调我):
There should be one– and preferably only one —obvious way to do it.
第二种方法是可行的,并且每个精通Python的人都应该知道(以及为什么),但这不是一种显而易见的方法,没有人在真实的代码中这样做.
那么为什么会这样呢?这就是方法在任何语言中的工作方式-方法是对对象/实例(可能还有更多参数)进行操作的一些代码.除了通常情况下,实例是隐式提供的(例如C / Java / D中的实例)-但由于Zen表示“显式优于隐式”,因此self是每个方法的显式参数,这不可避免.明确禁止它是没有意义的.
除此之外,无需强制(隐式地)使用实例的事实就可以在无需对语言进行特殊处理的情况下定义类方法和静态方法-第一个只是需要类而不是实例的方法,后者只是一种根本不需要实例的方法.
标签:instance,call,python,class,methods
来源: https://codeday.me/bug/20191209/2097175.html