Python:解释程序的结果

2024-05-14 04:29:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我的一个测试任务(为了获得初级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。 提前谢谢!你知道吗


Tags: selfdef职位actionpassprovidermethodclass
2条回答

这里有一个小贴士-不要一下子处理整个事情,要分门别类。你认为下面的代码应该做什么?是吗?你知道吗

>>> Super().method()
>>> Super.x
???

关键在于区分实例变量和类变量。你知道吗

循环:

for klass in (Inheritor, Replacer, Extender):
    klass().method() 

迭代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变量,并且实例是临时的,因此这些方法不做任何相关的事情。你知道吗

相关问题 更多 >