请考虑Python中的策略模式示例(从示例here改编而来)。在这种情况下,替代策略是一种功能。python方法如何自动接收'self'作为第一个参数?
class StrategyExample(object):
def __init__(self, strategy=None) :
if strategy:
self.execute = strategy
def execute(*args):
# I know that the first argument for a method
# must be 'self'. This is just for the sake of
# demonstration
print locals()
#alternate strategy is a function
def alt_strategy(*args):
print locals()
以下是默认策略的结果。
>>> s0 = StrategyExample()
>>> print s0
<__main__.StrategyExample object at 0x100460d90>
>>> s0.execute()
{'args': (<__main__.StrategyExample object at 0x100460d90>,)}
在上面的例子s0.execute
是一种方法(未一个普通的功能),并且因此在args
的第一个参数,如所预期,是self
。
以下是替代策略的结果。
>>> s1 = StrategyExample(alt_strategy)
>>> s1.execute()
{'args':()}
在这种情况下是s1.execute
一个普通的函数和作为预期的,不接收self
。因此args
是空的。等一下!这怎么发生的?
该方法和函数都以相同的方式调用。一个方法如何自动获得self
作为第一个参数?当一种方法被普通的香草函数取代时,而不是如何得到self
作为第一个参数?
我能找到的唯一区别是当我检查默认策略和替代策略的属性时。
>>> print dir(s0.execute)
['__cmp__', '__func__', '__self__', ...]
>>> print dir(s1.execute)
# does not have __self__ attribute
是否__self__
属性对s0.execute
(方法)上s1.execute
(功能)的存在,但缺乏它在某种程度上解释这种行为差异?这一切如何在内部工作?
你可以认为instance.method(ARG)'作为'InstanceClass.method的简写的'(实例,arg)'。 Python试图让事情尽可能简单明了,我发现这是一种“透明”的方式来访问实例,该实例称为函数 –