JAVA 因简洁而美丽,因有效而动人 善待JAVA这颗种子的人,必将得到她的福荫

Python中的继承

上一篇 / 下一篇  2013-10-06 17:40:27 / 个人分类:Python

转自:http://blog.csdn.net/delphiwcdj/article/details/5734688

派生类继承形式为:class DerivedClass(BaseClass):

 

[注意] 
[1] Python不会自动调用基类的constructor,我们要亲自专门调用它。在方法调用之前加上类名前缀,然后把self变量及其他参数传递给它。
[2] Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中查找。
[3] 基类是在派生类定义的时候,在元组之中指明的。
[4] 如果在继承元组中列了一个以上的类,那么它就被称作多重继承。

  1. #! /usr/bin/python  
  2. # Filename: inherit.py  
  3. # 2010-7-14 wcdj  
  4. class SchoolMember:  
  5.         '''''Represents any school member.'''  
  6.         def __init__(self, name, age):  
  7.                 self.name=name  
  8.                 self.age=age  
  9.                 print '(Initialized SchoolMember:%s)' % self.name  
  10.         def tell(self):  
  11.                 '''''Tell my details.'''  
  12.                 print 'Name:"%s" Age:"%s"' % (self.name, self.age), # note, this comma  
  13. class Teacher(SchoolMember):  
  14.         '''''Represents a teacher.'''  
  15.         def __init__(self, name, age, salary):  
  16.                 SchoolMember.__init__(self, name, age)  
  17.                 self.salary=salary  
  18.                 print '(Initialized Teacher:%s)' % self.name  
  19.         def tell(self):  
  20.                 SchoolMember.tell(self)  
  21.                 print 'Salary:"%d"' % self.salary  
  22. class Student(SchoolMember):  
  23.         '''''Represents a student.'''  
  24.         def __init__(self, name, age, marks):  
  25.                 SchoolMember.__init__(self, name, age)  
  26.                 self.marks=marks  
  27.                 print '(Initialized Student:%s)' % self.name  
  28.         def tell(self):  
  29.                 SchoolMember.tell(self)  
  30.                 print 'Marks:"%d"' % self.marks  
  31. t=Teacher('Mr. Young'4030000)  
  32. s=Student('wcdj'2275)  
  33. print # prints a blank line  
  34. members=[t, s]  
  35. for i in members:  
  36.         i.tell() # works for both Teachers and Students  
  37. #########  
  38. # output  
  39. #########  
  40. >>>   
  41. (Initialized SchoolMember:Mr. Young)  
  42. (Initialized Teacher:Mr. Young)  
  43. (Initialized SchoolMember:wcdj)  
  44. (Initialized Student:wcdj)  
  45. Name:"Mr. Young" Age:"40" Salary:"30000"  
  46. Name:"wcdj" Age:"22" Marks:"75"  



TAG: Python python

 

评分:0

我来说两句

Open Toolbar