python面向对象编程头哥
时间: 2023-12-04 20:41:47 浏览: 80
面向对象编程是一种编程范式,它将数据和操作数据的方法组合在一起,以便将数据和方法视为一个整体。Python是一种面向对象的编程语言,它支持面向对象编程的所有概念,例如类,对象,继承,多态等。以下是Python面向对象编程的一些基本概念和示例:
1.类和对象
类是一种用户定义的数据类型,它定义了一组属性和方法。对象是类的实例,它具有类定义的属性和方法。以下是一个简单的类和对象的示例:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print("Hello, my name is", self.name, "and I am", self.age, "years old.")
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
person1.say_hello() # 输出:Hello, my name is Alice and I am 25 years old.
person2.say_hello() # 输出:Hello, my name is Bob and I am 30 years old.
```
2.继承
继承是一种机制,它允许一个类继承另一个类的属性和方法。子类可以重写父类的方法或添加新的方法。以下是一个简单的继承示例:
```python
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def say_hello(self):
print("Hello, my name is", self.name, "and I am", self.age, "years old. I am in grade", self.grade)
student1 = Student("Alice", 15, 9)
student2 = Student("Bob", 16, 10)
student1.say_hello() # 输出:Hello, my name is Alice and I am 15 years old. I am in grade 9
student2.say_hello() # 输出:Hello, my name is Bob and I am 16 years old. I am in grade 10
```
3.多态
多态是一种机制,它允许不同的对象对相同的方法做出不同的响应。以下是一个简单的多态示例:
```python
def introduce(person):
person.say_hello()
person1 = Person("Alice", 25)
student1 = Student("Bob", 16, 10)
introduce(person1) # 输出:Hello, my name is Alice and I am 25 years old.
introduce(student1) # 输出:Hello, my name is Bob and I am 16 years old. I am in grade 10.
```
阅读全文