0

There is an interesting question on python 3.5. For example I've smth like:

class A:
  __x = 0
  def __init__(self, x):
    self.__x = x

  def set_x(self,x): __x=x
  def get_x(self): return x

class B(A):
  __y = 0
  def __init(self, x, y)
    self.__y = y
    super(B, self).__init__(x)

  def set_y(self,y): __y=y
  def get_y(self): return y

  def toString(self): return "x = {} and y = {}".format(self.__x,
                                                        self.__y); 
test = B(7,3)
test.toString()

Why do I have an error here: "B object has no attribute _B__x", if the method super() let me to use all methods of parante class?

Sure, if I write, like:

def toString(self): return "x = {} and y = {}".format(self.get_x(),
                                                      self.__y); 

It works well!

  • See http://stackoverflow.com/questions/20261517/inheritance-of-private-and-protected-methods-in-python - you shouldn't be using `__double_leading_underscore` names. – jonrsharpe Jan 17 '16 at 18:04
  • Also, your setters don't actually work. You always need to do `self.name = value`. `name = value` creates a local variable. – Kevin Jan 17 '16 at 18:05
  • Also also, there's no need to initialise instance attributes as class attributes, just set them in `__init__`. – jonrsharpe Jan 17 '16 at 18:10

1 Answers1

0

You do not get access to private variables/members through super(). So in order to access B.__x, you will have to do

def toString(self): return "x = {} and y = {}".format(self._B__x,
                                                    self.__y); 
Umer
  • 1