我的一个测试任务(为了获得初级python职位)说我必须解释程序的结果。代码是:
class SuperM: pass
SuperM.x = 0
class Super(SuperM):
def method(self):
self.x += 1
def delegate(self):
self.action()
class Inheritor(Super):
pass
class Replacer():
def method(self):
Super.x += 2
class Extender(Super):
def method(self):
Super.method(self)
class Provider(Super):
def action(self):
print self.x
if __name__ == '__main__':
for klass in (Inheritor, Replacer, Extender):
klass().method()
x = Provider()
x.delegate()
我该怎么写解释?为什么程序显示2
,而不是3
。
提前谢谢!你知道吗
这里有一个小贴士-不要一下子处理整个事情,要分门别类。你认为下面的代码应该做什么?是吗?你知道吗
关键在于区分实例变量和类变量。你知道吗
循环:
迭代3个类。它创建每个的(临时)实例并对其调用
method()
。让我们看看会发生什么:Inheritor().method()
创建Inheritor
的新实例并设置self.x = self.x + 1
。实例还没有x
属性,因此self.x
的读取通过继承返回到类变量SuperM.x == 0
,并将实例的x
设置为1。SuperM.x
保持不变。你知道吗Replacer().method()
-几乎相同的逻辑,读取Super.x
返回到SuperM.x == 0
,并将类变量Super.x
设置为2。你知道吗Extender().method()
是指Super.method()
尝试读取self.x
,返回到读取Super.x
(刚才设置为2),并将实例的self.x
设置为3。你知道吗然后
provider.action()
被调用,尝试打印self.x
,返回到读取Super.x
并打印2
。你知道吗请注意,
Replacer.method
是唯一一个指定名为x
的类变量的位置(除了开头)。此外,只修改实例x
变量,并且实例是临时的,因此这些方法不做任何相关的事情。你知道吗相关问题 更多 >
编程相关推荐