0

I have an abstract class that i will use as template to implement different kind of subclasses. I want to define some attributes/methods that are mandatory to all subclasses. For example

class BlockModel(ABC):

    def __init__(self, position):
        self.__position = position
        self.__lives = None
        self.__hitbox = None

    @property
    def lives(self):
        return self.__lives

    @lives.setter
    def lives(self, lives):
        self.__lives = lives

    @property
    def hitbox(self):
        return self.__hitbox

    @hitbox.setter
    def hitbox(self, hitbox):
        self.__hitbox = hitbox

    @abstractmethod
    def method1(self)
    #some abstract methods

    @abstractmethod
    def method2(self)
    #some abstract methods

When i create a subclass, for example

class Block1(BlockModel):

    def __init__(self,position_):
        super().__init__(position_)
        self.__lives=1
        self.__hitbox = pygame.Rect(self.__position['x'],
                                    self.__position['y'],
                                    5,
                                    5)

 #Implement abstract methods

The second class doesn't inherit the attributes __position, __lives, __hitbox, but the public ones without the underscores (i know that there are no real private attributes/methods in python). There s a way too keep them private(with underscores) in the subclass too?

  • 1
    The subclass does inherit them, but with name mangling; so `__position` becomes `_BlockModel__position`. This is what you're asking for when using double underscores. If you don't want to use this feature, use single underscores instead. – Patrick Haugh Sep 17 '19 at 13:50
  • Double-underscore names correspond to ``private``, not ``protected``. Use single-underscore names instead -- e.g. ``_position``. – MisterMiyagi Sep 17 '19 at 13:52
  • Possible duplicate of [Private members in Python](https://stackoverflow.com/questions/2064202/private-members-in-python) – MisterMiyagi Sep 17 '19 at 13:53

0 Answers0