1

In the below code,

>>> class Employee:

    numOfEmployees = 0 
    raiseAmount = 1.04 

    def __init__(self, firstName, lastName, pay):
        self.firstName = firstName
        self.lastName = lastName
        self.pay = pay
        self.email = firstName + '.' + lastName + '@arista.com'

        Employee.numOfEmployees += 1

    def fullName(self):
        return '{} {}'.format(self.firstName, self.lastName)

    def appyRaise(self):
        self.pay = int(self.pay * self.raiseAmount)

        @classmethod
        def setRaiseAmt(cls, amount):
            cls.raiseAmount = amount

        @classmethod
        def createEmployee(cls, employeeStr):
            firstName, lastName, pay = employeeStr.split('-')
            return cls(firstName, lastName, pay)

        @staticmethod
        def isWorkDay(day):
            if day.weekday() == 5 or day.weekday() == 6:
                return False
            return True

>>> class Developer(Employee):
           pass


>>> Developer.__dict__
{'__module__': '__main__', '__doc__': None}
>>> Employee.__dict__
{'__module__': '__main__', 'createEmployee': <classmethod object at 0x7f2727731398>, 'numOfEmployees': 0, 'setRaiseAmt': <classmethod object at 0x7f27277310f8>, 'isWorkDay': <staticmethod object at 0x7f27277313d0>, 'appyRaise': <function appyRaise at 0x7f2727721f50>, 'fullName': <function fullName at 0x7f2727721ed8>, '__doc__': None, '__init__': <function __init__ at 0x7f2727721e60>, 'raiseAmount': 1.04}
>>> 

Question:

Why Developer.__dict__ does not show members of Employee? What exactly are we doing with syntax class Developer(Employee)?

overexchange
  • 15,768
  • 30
  • 152
  • 347

2 Answers2

3

__dict__ is the attributes specifically defined on the subclass, not its parents. When an attribute is looked up on the subclass and not found, it will scan the MRO (method resolution order, the set of parent classes) until it finds one that does have the desired attribute. Copying everything from the parent to the child __dict__ would be wasteful on memory, and risk values getting out of sync (if the parent is monkey patched after the child is defined, and the child already cached a copy of the parent's __dict__ within its own, everything would break).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1

You are looking at the __dict__ of the class objects, not of the instances. If you look at the __dict__ of a Developer instance, you will see the inherited attributes. Methods (and class attributes) are resolved using the mro, as discussed at Method Resolution Order (MRO) in new style Python classes.

Community
  • 1
  • 1
cco
  • 5,873
  • 1
  • 16
  • 21