python面向对象举例
时间: 2023-07-14 21:03:59 浏览: 107
面向对象示例
当然,我可以给你一些 Python 面向对象的示例。
1. 类和对象:
```
class Car:
def __init__(self, brand, color):
self.brand = brand
self.color = color
def drive(self):
print(f"The {self.color} {self.brand} is driving.")
car1 = Car("BMW", "blue")
car1.drive()
```
2. 继承:
```
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Cat(Animal):
def speak(self):
print(f"{self.name} says 'Meow'.")
cat1 = Cat("Tom")
cat1.speak()
```
3. 多态:
```
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
print(f"{self.name} says 'Woof'.")
class Cat(Animal):
def speak(self):
print(f"{self.name} says 'Meow'.")
def make_animal_speak(animal):
animal.speak()
dog1 = Dog("Buddy")
cat1 = Cat("Tom")
make_animal_speak(dog1)
make_animal_speak(cat1)
```
这些是一些简单的示例,展示了 Python 中面向对象的基本概念。希望对你有帮助!如果你有更多问题,请随时提问。
阅读全文