【发布时间】:2017-05-11 02:45:54
【问题描述】:
dir/
|
|___ __init__.py
|
|___ Base_class.py
|
|___ Subclass.py
__init__.py 为空(如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
问题:
仅继承 Employee 类:
> python Subclass.py
为什么这是下面的输出?如何继承基类?
$ python Subclass.py
1.04
1.04
1.04
1.05
1.05
1.05
John.Doe@email.com
70000
False
【问题讨论】:
-
当你导入
Employeepythonruns时。因此文件末尾的所有print语句都将被执行。 -
@StephenRauch 所有打印语句都不属于
Employee。我只导入Employee -
不,您不仅在导入员工。评估整个文件....您仅所做的是将
Employee放入您的命名空间 -
@StephenRauch 如果整个文件有 100 个类,python 是否评估所有 100 个不相关的类以仅导入
Employee?评估整个文件需要什么?这很奇怪。首先,如果我写class Developer(Employee),我希望Developer.__dict__拥有Employee的所有成员。这是怎么回事? -
是的,而且所有的imports和imports中的imports....
标签: python python-2.7 inheritance