使用具有非匹配变量的类的Python多重继承

时间:2017-11-14 17:23:45

标签: python oop inheritance multiple-inheritance

如何使用带参数的类构造函数在python中设置多重继承?我已经看过许多没有arg构造函数的例子,但这并不好玩......我在c ++中完成了这个设置。我正在学习python并且想到我会尝试重新创建相同的设置。

如何在没有所有* args,* kwargs bs的情况下让我的Student_Worker构造函数工作?

如果覆盖适用于PersonStudentWorker,为什么它从StudentWorkerStudent_Worker不起作用?

如果钻石案例适用于4个构造函数中任何一个都没有参数的类,为什么它不能在构造函数中有参数的菱形框中工作?

我只是错过了一些简单的事情吗?我无法在任何地方找到合适的指南。

class Person:        #BASE CLASS
    num_of_persons = 0;

    def __init__(self,x,y,z):     
        Person.num_of_persons += 1   
        print("Greetings!")
        self.Name = x
        self.Sex = y
        self.DOB = z
        print("I am " + self.Name)    

    def get_info(self):       
        return '{} {} {}'.format(self.Name,self.Sex,self.DOB)


class Student(Person): #DERIVED CLASS
    def __init__(self, x, y, z, s):
        self.school = s
        return super().__init__(x, y, z)

    def get_info(self):
        return super().get_info() + ' {}'.format(self.school)


class Worker(Person):  #DERIVED CLASS
    def __init__(self, x, y, z, c):
        self.company = c
        return super().__init__(x, y, z)

    def get_info(self):
        return super().get_info() + ' {}'.format(self.company)



class Student_Worker(Student, Worker): #MULTIPLE DERIVED CLASS
    def __init__(self,x,y,z,s,c):
        Student.__init__(x,y,z,c)
        Worker.__init__(c)


p1 = Person("John","M", "1900")
s1 = Student("Sam","F","1910","iSchool")
w1 = Worker("Larry","M","1920","E-SITE")
sw1 = Student_Worker("Brandy","F","1930","iSchool","E-Site")

print(p1.get_info())
print(s1.get_info())
print(w1.get_info())
print(sw1.get_info())

1 个答案:

答案 0 :(得分:4)

您可以尝试按如下方式创建构造函数:

1)学生

select date(date_trunc('month', install_ts)) AS month, count(id) AS count from api_booking 

2)工人

class Student(Person): #DERIVED CLASS
    def __init__(self, x, y, z, s):
        Person.__init__(self,x, y, z)
        self.school = s

3)学生工作者

class Worker(Person):  #DERIVED CLASS
    def __init__(self, x, y, z, c):
        Person.__init__(self,x, y, z)
        self.company = c

如果您运行代码,您将获得此输出:

class Student_Worker(Student, Worker): #MULTIPLE DERIVED CLASS
    def __init__(self,x,y,z,s,c):
        Student.__init__(self,x,y,z,s)
        Worker.__init__(self,x,y,z,c)