python 面向对象编程案例
时间: 2023-09-05 21:09:55 浏览: 116
python 零基础学习篇面向对象编程案例学员管理20 加载学员信息.mp4
以下是一个简单的 Python 面向对象编程案例:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"My name is {self.name} and I am {self.age} years old.")
class Student(Person):
def __init__(self, name, age, major):
super().__init__(name, age)
self.major = major
def introduce(self):
print(f"My name is {self.name}, I am {self.age} years old, and I major in {self.major}.")
class Teacher(Person):
def __init__(self, name, age, subject):
super().__init__(name, age)
self.subject = subject
def introduce(self):
print(f"My name is {self.name}, I am {self.age} years old, and I teach {self.subject}.")
# 创建对象
person1 = Person("Tom", 25)
student1 = Student("Jerry", 20, "Computer Science")
teacher1 = Teacher("John", 30, "Mathematics")
# 调用方法
person1.introduce()
student1.introduce()
teacher1.introduce()
```
此代码定义了一个 `Person` 类,以及两个子类 `Student` 和 `Teacher`。每个类都有一个 `introduce` 方法,用于打印该对象的信息。然后创建了三个对象,分别是普通人、学生和老师,并调用了他们的 `introduce` 方法。
输出结果为:
```
My name is Tom and I am 25 years old.
My name is Jerry, I am 20 years old, and I major in Computer Science.
My name is John, I am 30 years old, and I teach Mathematics.
```
这个案例展示了 Python 面向对象编程的一些基本概念,包括继承、多态和方法重写。
阅读全文