dir/
|
|___ __init__.py
|
|___ Base_class.py
|
|___ Subclass.py
__init__.py
是空的(如所提到的here)如何繼承一個python基類?
/* 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
問題:
在剛剛繼承Employee
類:
> python Subclass.py
爲什麼下面的輸出?如何繼承基類?
$ python Subclass.py
1.04
1.04
1.04
1.05
1.05
1.05
[email protected]
70000
False
當你導入'僱員'python' runs'它。因此,文件末尾的所有'print'語句都將被執行。 –
@StephenRauch所有打印語句不是「員工」的一部分。我只輸入'Employee' – overexchange
不,你不只是輸入Employee。評估整個文件....只是*你的*只是將'Employee'放入你的命名空間 –