【发布时间】:2011-10-02 19:33:48
【问题描述】:
考虑这个 Python 中的策略模式示例(改编自示例 here)。在这种情况下,备用策略是一个函数。
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
s0.execute(方法)上存在__self__ 属性,但s1.execute(函数)上没有它,是否以某种方式解释了这种行为差异?这一切在内部如何运作?
【问题讨论】:
-
您可以将
instance.method(arg)视为InstanceClass.method(instance, arg)的简写。 Python 试图让事情尽可能简单明了,我发现这是一种访问调用函数的实例的“透明”方式