有没有一种方法可以将变量动态地分类到类中?

时间:2019-06-17 18:05:18

标签: python-3.x class

我有这两个类:“雇员”(超类)和“推销员”(“雇员”的子类)。

我有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

1 个答案:

答案 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文件导入员工数据,我以后会遇到问题吗?

相关问题