Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Python single and double underscore variables

I am unsure what I am doing wrong; or why this is the case.

I've the following code:

class Expression (Node):
  """
  ...
  """

  def __init__ (self):
    self.__expressionType = None


  def expressionType (self):
    return self.__expressionType


class Number (Expression):
  """
  Number .
  """

  def __init__ (self, value):
    """
    Value is an entry of type Constant.
    """
    Expression.__init__(self)
    assert isinstance (value, KST.Constant)
    self.__constant = value
    self.__expressionType = value.elementType()

For a number object say n = Number(KST.Constant(..)), I am always returned None for the following statement—

 n.expressionType()

Now if I change the double underscores to single ones, it all works. I understand the difference between private and semi-private variables but why this is happening — I've no idea. Also, I've used "__" in a number of other places and it all seems to work fine.

like image 618
p0lAris Avatar asked Apr 01 '13 05:04

p0lAris


1 Answers

Attribute names with double underscores are "mangled" to make it harder to have conflicting name in subclasses.

So use single underscores.

like image 155
Lennart Regebro Avatar answered Sep 29 '22 00:09

Lennart Regebro