对Python中的超级函数和自相混淆

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对Python中的超级函数和自相混淆相关的知识,希望对你有一定的参考价值。

这里是代码使我感到困惑。

#python3 code
class SuperClass():
    def __init__(self,a):
        self.a = a

class SubClass(SuperClass):
    def __init__(self,a):
        self.a = a
        super(SubClass,self).__init__(a+1)


if __name__ == '__main__':
    sub = SubClass(1)
    print(sub.a) # result is 2
    # print(super(SubClass,sub).a) # AttributeError: 'super' object has no attribute 'a'

我想在调用super(SubClass,self).__init__(a+1)时,对象sub传递给SuperClass中的self不是子对象的父对象

我有2个问题:

  1. 我的猜测正确吗?如果正确,为什么要这样设计?如果不是,什么是正确的机械装置?
  2. 我如何将值a + 1传递给SuperClass.a,换句话说,使super(SubClass,sub).a=2

谢谢

编辑1

对代码感到抱歉。我将self.a=asuper(SubClass,self).__init__(a+1)两行放错了地方。我已经纠正了上面的代码,它仍然支持我的猜测。

编辑2

#Let me explain my doubt in detail
#Generally We have a class Clazz
class Clazz():
    def f(self,a):
        pass
# and it's instance c
c = Clazz();
# when invoke method f of instance c, instance should be  implicit pass to the method as first parameter.
c.f(1) # formally equivalent to c.f(c,1)

#then back to my case
#In my logic
# super(SubClass,self) is a instance of class super ,when it invokes method __init__
# Similarly super(SubClass,self).__init__(a+1) should be equivalent to super(SubClass,self).__init__(super(SubClass,self),a+1)
class SuperClass():
    def __init__(self,a):   #  self=super(SubClass,sub)
        self.a = a          #  formally equivalent to super(SubClass,sub).a = a

# however it's not like as i thought
# super(SubClass,self).__init__(a+1) formally equivalent to super(SubClass,self).__init__(sub,a+1)
class SuperClass():
    def __init__(self,a):   #  self=sub
        self.a = a          #  formally sub.a = a
# it's contradictory
答案
简短的回答:不可能。

长答案:您的SubClass继承自SuperClass。初始化sub的对象SubClass时,它将进入__init__SubClass。在那里它告诉它运行__init__SuperClass,其中sub.a的值设置为2,但是在SubClass中立即将值1写入sub.a

sub.a被覆盖。没了该变量仅存在一次,而不是两次。在这种情况下,您的SubClass和SuperClass引用相同的变量sub.a

如果要保留值,则需要定义一个新变量并在其中写入值。

#python3 code class SuperClass(): def __init__(self,var): self.a = var class SubClass(SuperClass): def __init__(self,var): super(SubClass,self).__init__(var+1) self.b = var if __name__ == '__main__': sub = SubClass(1) print(sub.a) print(sub.b)

以上是关于对Python中的超级函数和自相混淆的主要内容,如果未能解决你的问题,请参考以下文章

Python 默认参数混淆

超级有用的9个PHP代码片段

代码混淆

带有复选框和自定义适配器的 ListView,片段无法正常工作

python基础篇(二十)——Python中的一些易混淆点总结(完结)

Python程序代码混淆、编译、打包、运行(桌面程序防破解向)