dir/
|
|___ __init__.py
|
|___ Base_class.py
|
|___ Subclass.py
__init__.py
is empty(as mentioned here)
/* Base_class.py
class Employee:
numOfEmployees = 0 # Pure class member, no need to override
raiseAmount = 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 methods
def __init__(self, firstName, lastName, pay):
self.firstName = firstName
self.lastName = lastName
self.pay = pay
self.email = firstName + '.' + lastName + '@email.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
emp1 = 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 updated
print Employee.raiseAmount # 1.05
print emp1.raiseAmount # 1.05
print emp2.raiseAmount # 1.05
emp1.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 Employee
class 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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…