Python Multiple Inheritance using Classes with non matching variables
如何使用带有参数的类构造函数在Python中设置多个继承?我看到过很多没有arg构造函数的例子,但这并不有趣…我已经在C++中完成了这个设置。我正在学习python,我想我会尝试重新创建相同的设置。
我怎样才能让我的学生-工人-建造师在没有所有的args,kwargs-bs的情况下工作?
如果覆盖从
如果diamond case在4个构造函数中的任何一个中都没有参数的类上工作,为什么它不在一个在构造函数中有参数的diamond case中工作呢?
我只是缺少一些简单的东西吗?我找不到像样的导游。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | 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)学生
1 2 3 4 | class Student(Person): #DERIVED CLASS def __init__(self, x, y, z, s): Person.__init__(self,x, y, z) self.school = s |
2)工人
1 2 3 4 | class Worker(Person): #DERIVED CLASS def __init__(self, x, y, z, c): Person.__init__(self,x, y, z) self.company = c |
号
3)学生工
1 2 3 4 | 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) |
如果运行代码,将得到以下输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Greetings! I am John Greetings! I am Sam Greetings! I am Larry Greetings! I am Brandy Greetings! I am Brandy John M 1900 Sam F 1910 iSchool Larry M 1920 E-SITE Brandy F 1930 E-Site iSchool |
。