Why can't I access superclass private variables in Python?

I know that I have to use access methods. I see in the module datetimethat the class datetimeinherits from the date.

class datetime(date):
    <some other code here....>
    self = date.__new__(cls, year, month, day)
    self._hour = hour
    self._minute = minute
    self._second = second
    self._microsecond = microsecond
    self._tzinfo = tzinfo
    return self

I also see that datetime has access to date members, as in __repr__:

def __repr__(self):
    """Convert to formal string, for repr()."""
    L = [self._year, self._month, self._day, # These are never zero
         self._hour, self._minute, self._second, self._microsecond]

I tried to subclass datetime to add some information to it, and then write a similar function __repr__:

def __repr__(self):
    """Convert to formal string, for repr()."""
    L = [self._year, self._month, self._day, # These are never zero
         self._hour, self._minute, self._second, self._microsecond,
         self._latitude, self._longitude]

The debugger complained that self._year did not exist. ( self.yearworks, however.)

I know that I have to use the access function. I just want to understand why it datetimehas access to private variables date, but my subclass cannot.

+5
source share
2

datetime.py, :

try:
    from _datetime import *
except ImportError:
    pass

, , C- python, , , .

+4

datetime

. datetime / . .

, , datetime / ( ).

0

All Articles