python subclass access to class variable of parent

前端 未结 2 1172
情话喂你
情话喂你 2020-12-01 04:37

I was surprised to to learn that a class variable of a subclass can\'t access a class variable of the parent without specifically indicating the class name of the parent:

2条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 05:08

    In Python, the body of a class is executed in its own namespace before the class is created (after which, the members of that namespace become the members of the class). So when the interpreter reaches y = x+1, class B does not exist yet at that point and, therefore, has no parent.

    For more details, see http://docs.python.org/reference/compound_stmts.html#class-definitions

提交回复
热议问题