0
class People:
    # parent to both Employee and Customer classes
    def __init__(self, id, name, ssn): # define class People
                                       # self used to accesses attributes and methods in class
    # set instance variable
        self.__id = id
        self.__name = name
        self.__ssn = ssn

class Employee(People):
    #Child of Class People
    def __init__(self, id, name, ssn, password):
        People.__init__(self, id, name,ssn)
        self.__password = password

    def __str__(self):
        return f"ID :{self.__id}\nName :{self.__name}\nSSN :{self.__ssn}\nPassword :{self.__password}"
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

Naming variable with double underscore prefix (e.g. __somename) triggers python "name mangling". This is intended to prevent name collision, and as a result, Python requires a special attribute name to access: _ClassName__somename instead of __somename.

For example:

class Person():
   def __init__(self, name):
        self.__name = name

>>> Person("x").__name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Person' object has no attribute '__name'
>>> Person("x")._Person__name
'x'

To fix this you should either use the "mangled" name to access, or rename your variables to remove the double underscore.

For more details see this detailed stackoverflow post on this topic .

gtalarico
  • 4,409
  • 1
  • 20
  • 42
  • There is no such thing as "private" in python. Don't confuse name mangling with private. A single leading undescore means "should be private" by convention. Name mangling is a way to prevent name colisions. – buran Dec 12 '21 at 20:51
  • Although it's actually not private, people do use `__` to "hide" or make their variables "slightly more private" or harder to access. If you search "python make variable private" you will find a lot of content suggesting "__name" as a solution. But it's a fair point that this is confusing. I revised the text to clarify – gtalarico Dec 12 '21 at 20:59
  • And, from a style point of view, should use `super()` instead of invoking `People.__init__()` – scooter me fecit Dec 14 '21 at 22:18