我有这两个类:“雇员”(超类)和“推销员”(“雇员”的子类)。
我有eric = ('Eric', 19, 'Salesman', 1700)
。
我可以使用函数检查Eric是否是推销员,并将其动态分配给“雇员”超类或“推销员”子类吗?
那我应该怎么写呢?
我希望,我对问题的描述不会太混乱。
class Employee():
'''the employee superclass'''
def __init__(self, name, age, occupation, monthly_pay):
self.isemployee = True
self.name = name
self.age = age
self.occ = occupation
self.pay = monthly_pay
class Salesman(Employee):
'''the Salesman subclass'''
def __init__(self):
self.issalesman = True
答案 0 :(得分:1)
经过反复试验和重写,这是我想到的:
class Employee():
'''The employee superclass'''
def __init__(self, name, age, occupation, monthly_pay):
self.name = name
self.age = age
self.occ = occupation
self.pay = monthly_pay
class Salesman(Employee):
'''The Salesman subclass'''
def issalesman(self):
self.issalesman = True
def class_assigner(person):
if person[2] == 'Salesman':
person = Salesman(person[0], person[1], person[2], person[3])
else:
person = Employee(person[0], person[1], person[2], person[3])
return person
print(class_assigner(eric).occ)
输出:
推销员
这是一种可行的方法吗?或者,如果我说开始从.txt或.csv文件导入员工数据,我以后会遇到问题吗?