dir/||___ __init__.py||___ Base_class.py||___ Subclass.py
__init__.py
is empty(as mentioned here)
/* Base_class.pyclass Employee:numOfEmployees = 0 # Pure class member, no need to overrideraiseAmount = 1.04 # Could not be pure class member, so, can it be overidden by object?# Yes. make sense# This is why we use self.raiseAmount in methodsdef __init__(self, firstName, lastName, pay):self.firstName = firstNameself.lastName = lastNameself.pay = payself.email = firstName + '.' + lastName + '@email.com'Employee.numOfEmployees += 1def fullName(self):return '{} {}'.format(self.firstName, self.lastName)def appyRaise(self):self.pay = int(self.pay * self.raiseAmount)@classmethoddef setRaiseAmt(cls, amount):cls.raiseAmount = amount@classmethoddef createEmployee(cls, employeeStr):firstName, lastName, pay = employeeStr.split('-')return cls(firstName, lastName, pay)@staticmethoddef isWorkDay(day):if day.weekday() == 5 or day.weekday() == 6:return Falsereturn Trueemp1 = Employee('AAA', 'BBB', 50000)
emp2 = Employee('CCC', 'DDD', 40000)print Employee.raiseAmount # 1.04
print emp1.raiseAmount # 1.04
print emp2.raiseAmount # 1.04# Regular methods
emp1.fullName() # Executing fullName(<__main__.Employee object at 0xb7dbef0c>)
Employee.fullName(emp1) # same as above # With classmethods, the class of the object instance is implicitly passed as the first argument instead of self.Employee.setRaiseAmt(1.05) # class variable's cls member raiseAmount will get updatedprint Employee.raiseAmount # 1.05
print emp1.raiseAmount # 1.05
print emp2.raiseAmount # 1.05emp1.setRaiseAmt(1.05) # Invokes as, setRaise(<class '__main__.Employee'>,1.05)# Application of class methods as constructors
employeeStr = 'John-Doe-70000'
newEmployee = Employee.createEmployee(employeeStr);print newEmployee.email
print newEmployee.pay# With static methods, neither self (the object instance) nor cls (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:emp1 = Employee('AAA', 'BBB', 50000)
emp2 = Employee('CCC', 'DDD', 40000)import datetime
myDate = datetime.date(2016, 7, 10)print emp1.isWorkDay(myDate) # Executing isWorkDay(myDate)
/* Subclass.py */from Base_class import Employeeclass Developer(Employee):pass
Question:
On just inheriting Employee
class:
> python Subclass.py
why this below output? How to inherit base class?
$ python Subclass.py
1.04
1.04
1.04
1.05
1.05
1.05
[email protected]
70000
False