python多重继承:避免属性命名冲突

python多重继承:避免属性命名冲突,python,multiple-inheritance,Python,Multiple Inheritance,假设我有两个班Employee和Student: class Employee(): def __init__(self, id): self.id = id # the employee id ...methods omitted... class Student(): def __init__(self, id): self.id = id # the student id, different from employee

假设我有两个班
Employee
Student

class Employee():
    def __init__(self, id):
        self.id = id  # the employee id

    ...methods omitted...   

class Student():
    def __init__(self, id):
        self.id = id  # the student id, different from employee id

    ...methods omitted...
现在我想创建第三个类
StudentEmployee
,它简单地合并
Employee
Student

但是,目标是在每个继承的类中都保留
id

像这样的事情:

class StudentEmployee(Employee, Student):
    def __init__(self, employee_id, student_id):
        Employee.__init__(self, employee_id)
        Student.__init__(self, student_id)  # overrides employee id
请注意,
Student
Employee
都具有
id
属性,因此实际上一个将覆盖另一个

问题:

我如何保持这两个
id
,因为它们具有不同的含义

例如,是否有某种方法可以防止一个类的
id
被另一个类覆盖

方法1 一种自然的方法是将类定义更改为:

class Employee():
    def __init__(self, id):
        self.eid = id  # now "id" changes to "eid"

    ...attributes names in methods updated as well   

class Student():
    def __init__(self, id):
        self.sid = id  # now "id" changes to "sid"

    ...attributes names in methods updated as well   
但是,我不太喜欢这种方法,因为
eid
不如
sid
整洁

此外,上面的例子可能过于简单

让我们设想两个被“合并”的类有多个共享属性名,代码重构工作不会很小


还有其他更好的方法吗?

使用组合,而不是以双下划线开头的继承或“私有属性”。但是在子类中访问会有点困难。例如,
StudentEmployee
的一个实例,
se.id
应该返回什么?如果合成不起作用,可能是Employee和Student都从中继承的一个基类,它包含了它们的共享属性?很显然,关于这个新对象如何工作的信息还不够。你们需要回答你们的问题并提供更多的信息。作文解决了我的问题。谢谢