Home > database >  Error trying to access a parent variable from his child class
Error trying to access a parent variable from his child class

Time:10-29

So I have this class:

class UniversalHash(HashClass):
    
    ##################################################
    
    def __init__(self):
        super().__init__()
        self.__MParamK = int(0)
        self.__MParamC = int(0)
        self.__MParamD = int(0)
        
    # Override # 
    def FindHash(self, Key): 
        return (((self.__MParamK * Key)   self.__MParamC) % self.__MParamD) % self.__MParamL
    
    def SetParamK(self, Value):
        self.__MParamK = Value
        
    def SetParamC(self, Value):
        self.__MParamC = Value
        
    def SetParamD(self, Value):
        self.__MParamD = Value

And the parent class:

class HashClass:
    
    ##################################################
    
    def __init__(self):
        self.__MParamL = int(0)
        
    def SetParamL(self, Value):
        self.__MParamL = Value
    
    def GetParamL(self):
        return self.__MParamL
    
    def FindHash(self, Key):
        pass

When I try to access to the variable __MParamL (the variable created in the parent), it gives me an exception telling me that the variable is not an attribute of this class, I have searched on the web and it seems this is the correct way to write the code (maybe the overridden function is the problem?). Any help is appreciated

CodePudding user response:

When you name an instance attribute with a leading double underscore, it will get name mangled, E.g.,

>>> class A:
...    def __init__(self):
...      self.x = 42
...      self.__y = 42
...
>>> a = A()
>>> vars(a)
{'x': 42, '_A__y': 42}

Instead, you should just use a single underscore, E.g.,

>>> class A:
...   def __init__(self):
...     self.x = 42
...     self._y = 42
...
>>> a = A()
>>> vars(a)
{'x': 42, '_y': 42}
  • Related