X
X
xdgadd2017-04-23 21:44:59
Python
xdgadd, 2017-04-23 21:44:59

Why do functions that operate on restricted members of a child class require overloading to work correctly?

Let's say there are 2 classes: BaseClass and ChildClass.
If you overload a protected variable in the constructor of the child class,
it will not be updated in the methods inherited from the base:

class BaseClass(object):

    def __init__(self, param):
        self.public = param
        self.another_public = 'Another public param'
        self.__protected = "Protected param"
    
    def getProtectedParam(self):
        return self.__protected

    def printProtected(self):
        print(self.__protected)

    def printPublic(self):
        print(self.public)

    def printAnother(self):
        print(self.anotherPublic)

class ChildClass(BaseClass):

    def __init__(self, param, newpub):
        super().__init__(param)

        # Переопределяю переменные
        self.another_public = newpub
        self.__protected = 'New protected param'

    def newPrintFunc(self):
        print(self.__protected)

if __name__ == '__main__':
    base = BaseClass('Public param')
    base.printPublic()
    base.printAnother()
    base.printProtected()
    print(base.getProtectedParam(), '\n')

    child = ChildClass("Child public param", "New another public param")
    child.printPublic() # Public param
    child.printAnother() # New another public param
    child.printProtected() # Protected param
    print(child.getProtectedParam()) # Protected param
    child.newPrintFunc() # New protected param

If you overload the getProtectedParam method, then a new value will be returned:
# Теперь printProtected выводит New protected param
    def printProtected(self):
        print(self.__protected)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2017-04-23
@xdgadd

I'm too lazy to even read such questions.
Not protected in python.
No.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question