Python面向对象编程:实例解析
面向对象编程(Object-Oriented Programming,OOP)是程序设计的一种范式。在Python中,OOP的主要特性包括:
封装(Encapsulation):
- 将数据和操作数据的方法绑定在一起。
- 只能通过特定的接口访问数据。
```python
class BankAccount:def __init__(self, account_number):
self.account_number = account_number
self.balance = 0
# 调用方法,实现封装
def deposit(self, amount):
if amount > 0:
self.balance += amount
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if amount > 0 and self.balance >= amount:
self.balance -= amount
else:
print("Withdrawal amount must be positive and within balance.")
继承(Inheritance):
- 允许一个类(子类)继承另一个类(父类)的属性和方法。
```python
class Animal:def __init__(self, name):
self.name = name
# 父类通用方法
def speak(self):
return "The animal speaks."
class Dog(Animal): # 子类继承父类
def speak(self):
return super().speak() + " Woof!"
多态(Polymorphism):
- 即同一接口可以有不同的实现方式,使代码更加灵活。
class Shape:
def area(self):
pass # 假设每个形状都有area方法
class Circle(Shape):
def area(self):
return math.pi * (self.radius ** 2))
class Rectangle(Shape):
def area(self):
return self.width * self.height
shape1 = Circle(radius=5)
shape2 = Rectangle(width=10, height=5))
print(shape1.area()) # 输出:78.539816339745
print(shape2.area()) # 输出:50
以上就是Python面向对象编程中的实例解析,通过创建类和实例化,实现了数据的封装、继承以及多态等特性。
还没有评论,来说两句吧...