Python inheritance exit

class ParentClass(object):
    def __init__(self):
        self.__x = 1
        self.y = 10
    def PRINT(self):
        print (self.__x, self.y)

class ChildClass(ParentClass):
    def __init__(self):
        super(ChildClass, self).__init__()
        self.__x = 2
        self.y = 20


c = ChildClass()
c.PRINT()

      

Why is the conclusion (1, 20)? I know how I get 20, but shouldn't it be 2 instead of 1?

+3


source to share


3 answers


Just to expand on the challenge a little ...

From the official Python tutorial

Any identifier of the form __spam (at least two leading underscores, no more than one underscore) is replaced with the text _classname__spam, where classname is the current class name, separated by underscores. This manipulation is performed without regard to the syntactic position of the identifier, if it occurs in the class definition.

So, if we add this line to the end of your code:



print c._ChildClass__x, c._ParentClass__x,

      

it will print

(1, 20)
2 1

      

+3


source


Members beginning with two underscores are "private". While Python has no real way to restrict access to members, it does some name to give them a more complex name so that they remain more or less private.

So in your case ParentClass

has a field __x

that is used in the method PRINT

. And it ChildClass

has a separate independent field __x

that is not used anywhere. Therefore, only parents are used for printing __x

.



To fix this, simply change the two underscores to one underscore to mark the name as "internal" but not type-locked.

+2


source


The variable 'private' ( __

as a prefix) in the class has been renamed. You can use a new name for the corresponding call variable. Like this:

#!/usr/bin/python
# -*- coding: utf-8 -*-

class ParentClass(object):
    def __init__(self):
        self.__x = 1
        self.y = 10
    def PRINT(self):
        print (self.__x, self.y)
        print (self._ParentClass__x, self.y)
        print (self._ChildClass__x, self.y)

class ChildClass(ParentClass):
    def __init__(self):
        super(ChildClass, self).__init__()
        self.__x = 2
        self.y = 20


c = ChildClass()
c.PRINT()

      

OUTPUT:

(1, 20)
(1, 20)
(2, 20)

      

0


source







All Articles