By looking at below example, it is easy to learn how a class inherits from other classes and how a class is declared, defined and used in Python.
--------------------------------
Python là một ngôn ngữ lập trình hướng đối tượng! bên dưới là một ví dụ đơn giản về tính thừa kế trong Python.
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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | """ -------------------------------------------------- mathhoang (mathhoang.blogspot.com) -------------------------------------------------- This example is to demonstrate the inheritance in Python. In this example, we have one parent class and 2 children classes which inherit their parent classe (particularly, it is person in our case) Super class: person has first and last name and a method called "getName" child class 1: Employee does not only have has first and last name, but also has staff number child class 2: Boss: has first, last name and title person | | +-------------+ | | Employee Boss """ import sys #----- Parent class: person -------- class person: def __init__(self,first,last): self.firstName = first self.lastName = last def getName(self): return self.firstName + " " + self.lastName #----- child class: Employee inherited from person -------- class Employee(person): def __init__(self,first,last,staffNum): person.__init__(self,first,last) self.staffNum = staffNum def getEmployee(self): return self.getName() + ": " + self.staffNum #----- child class: Employee inherited from person -------- class Boss(person): def __init__(self,first,last,title): person.__init__(self,first,last) self.title = title def getBoss(self): return self.getName() + ": Employee ID: " + self.title def main(): #----- instantiate class -------- person_1 = person("Math", "Hoang") Employee_1 = Employee("Math", "Hoang", "12344") Employee_2 = Employee("Blog", "spot", "43211") Boss_ = Boss("Mathhoang", "Blogspot.com", "CEO") #------ print out information ------ print(person_1.getName()) print(Employee_1.getEmployee()) print(Employee_2.getEmployee()) print(Boss_.getBoss()) if __name__ == '__main__': sys.exit(main()) |
No comments:
Post a Comment