简体   繁体   中英

Inheritance, parent class setter rewrites child's property

I have Child class which extends Parent, the latest implements property descriptor and rewrites the attribute (self.child_prop) that Child class has.

I can't change Parent class implementation and I need to use attribute with the same name. Current structure suggest that property 'setter' receives 'self' of Child class therefore gets access to upper level attributes. Is there any way to prevent Parent from accessing Child's attributes?

class Parent(object):

    def __init__(self):
        self.parent_prop = 'parent prop initialized'

    def _setter(self,val):
        self._local_parent_prop = val
        self.child_prop = 'child value changed from parent'
        print 'mro of Parent class: {0}'.format(Parent.__mro__)
        print 'self in Parent belongs to {0}'.format(self.__class__)

    def _getter(self):
        print 'getting prop from parent'
        return self._local_parent_prop

    parent_body = property(_getter,_setter)


class Child(Parent):
    def __init__(self):
        self.child_prop = 'child prop initialized'
        super(Child,self).__init__()


child = Child()
print child.child_prop
child.parent_body = 'setting parent property'
print child.child_prop # here attribute was changed from Parent

Output:

child prop initialized
mro of Parent class: (<class '__main__.Parent'>, <type 'object'>)
self in Parent belongs to <class '__main__.Child'>
child value changed from parent

Is there any way to prevent Parent from accessing Child's attributes?

No. That is not in Python philosophie. You can ask for any attribute on any object, and if it exists the interpretor will use it. That means that if a parent class can know that the current object is in fact a subclass instance or has a specific attribute whatever the reason, it can access it.

But as a programmer you should not: accessing a child class attribute from a parent class is really bad practice because it break the encapsulation princips.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM