1、面向对象的概念
1.1类
技术解释:类是定义对象的模版或蓝图。它定义了对象的属性(数据)和行为(方法或功能)。
举例:你可以把类想象成是一个蓝图或者是食谱。比如,一个蛋糕的食谱会告诉你需要哪些原料和制作方法,但食谱本身不是蛋糕。
class Cake: # 对类命名一般首字母大写
pass # 占位符
cake_1 = Cake() # 用 Cake 模板制作成 cake_1
cake_2 = Cake() # 用 Cake 模板制作成 cake_2
print(cake_1) # 输出cake_1 内存地址
print(cake_2) # cake_2内存地址
1.2属性
技术解释:属性是类或对象的变量,它存储了关于对象的信息或状态。
举例:车的颜色、品牌、型号等信息就是车的属性。它们描述了车的特征。
class Car:
def __init__(self): # 实例化时会被类自动执行
self.color = "red" # 指类本身的color属性
self.bind = "BYD"
self.model = "A1"
print("正在定义一辆车")
car_1 = Car() # 实例化
print(car_1.color)
print(car_1.bind)
print(car_1.model)
1.3行为
技术解释:行为通常是类中定义的方法,它描述了对象可以执行的操作。
举例:汽车可以启动、加速和刹车。这些都是汽车的行为,描述了汽车可以做什么。
class Car:
def __init__(self): # 实例化时会被类自动执行
self.color = "red" # 指类本身的color属性
self.bind = "BYD"
self.model = "A1"
print("正在定义一辆车")
def start(self):
print(f"{self.bind}正在启动")
def forward(self, meter):
print(f"{self.bind}正在向前{meter}米")
def stop(self):
print(f"{self.bind}正在停止")
car_1 = Car() # 实例化
car_1.start()
car_1.forward(100)
car_1.stop()
1.4对象
技术解释:对象是类的实例。你可以根据一个类创建多个对象,每个对象都有自己的属性(数据)和行为(方法)。
举例:如果类是蛋糕的食谱,那么对象就是根据食谱制作出来的实际的蛋糕。你可以根据同一个食谱制作出许多蛋糕,每个蛋糕都是一个对象。
class NeuralNetwork:
def __init__(self, weights, bias):
print("我是神经网络")
self.w = weights # 权重
self.b = bias # 偏置
def forward(self, x):
"""前向传播函数"""
print(f"已经接收到输入{x}")
print("正在前向传播")
y = self.w * x + self.b
return y
def show_parameters(self):
print("我的网络参数如下:")
print(f"self.w = {self.w}")
print(f"self.b = {self.b}")
# network_1
network_1 = NeuralNetwork(2, 3)
network_1.show_parameters()
result_1 = network_1.forward(2)
print(result_1)
# network_2
network_2 = NeuralNetwork(4, 5)
network_2.show_parameters()
result_2 = network_2.forward(2)
print(result_2)
2、面向对象的特征
2.1封装
技术解释:封装是指将对象的状态(属性)和行为(方法)包装在一起,并限制外部直接访问对象的内部细节(例如,直接修改对象的某个属性)。通过封装,对象的内部实现可以自由修改,而不影响到外部代码。
举例:就像我们去银行通过柜员机取钱,我们只需要输入账号密码,还有取款金额,就可以拿到钱,里面的细节我们不需要了解。
class BankAccount:
def __init__(self, initial_balance=0):
self.balance = initial_balance
def deposit(self, amount):
"""存钱函数"""
if amount > 0:
self.balance += amount
return True
return False
def withdraw(self, amount):
"""取款函数"""
if 0 < amount <= self.balance:
self.balance -= amount
return True
return False
def get_balance(self):
"""显示余额"""
return self.balance
# 创建一个银行账户
account = BankAccount(1000)
success_deposit = account.deposit(50)
print(f"success_deposit = {success_deposit}")
success_withdraw = account.withdraw(500)
print(f"success_withdraw = {success_withdraw}")
print(f"目前余额为:{account.get_balance()}")
2.2继承
技术解释:在面向对象编程(OOP)中,继承是一种机制,允许我们定义一个新的类(子类)基于一个已有的类(父类)。子类继承了父类的属性和方法,并可以添加自己的属性和方法,或重写父类的方法以实现不同的行为。
剧烈:扩展之前的例子,在BankAccount基础上,做出可以计算利息的SavingAccount
class BankAccount:
def __init__(self, initial_balance=0):
self.balance = initial_balance
def deposit(self, amount):
"""存钱函数"""
if amount > 0:
self.balance += amount
return True
return False
def withdraw(self, amount):
"""取款函数"""
if 0 < amount <= self.balance:
self.balance -= amount
return True
return False
def get_balance(self):
"""显示余额"""
return self.balance
class SavingAccount(BankAccount):
def __init__(self, initial_balance, interest_rate):
super().__init__(initial_balance) # 对父类进行初始化
self.interest_rate = interest_rate
def add_interest(self):
interest = self.balance * self.interest_rate / 100
self.balance += interest
return interest
saving_account = SavingAccount(100, 5)
interest = saving_account.add_interest()
new_balance = saving_account.get_balance()
print(interest, new_balance)
2.3多态
技术解释:多态是指不同类的对象对同一消息(方法调用)可以做出不同的响应。这意味着不同类的对象可以使用相同的接口(方法名),但具体实现(方法的内部代码)可以不同。
举例:同样是计算面积,圆形和矩形的计算方法有所不同。
class Shape:
def area(self):
return 0
class Circle(Shape):
"""圆形"""
def __init__(self, radius):
self.radius = radius # 半径
def area(self):
return 3.14159 * self.radius * self.radius
class Rectangle(Shape):
"""矩形"""
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def print_area(shape):
print(f"The area of the shape is {shape.area()}")
circle = Circle(5)
rectangle = Rectangle(10, 5)
print_area(circle)
print_area(rectangle)
3、综合案例
3.1综合案例:神经网络的继承
class NeuralNetwork:
def __init__(self, input_layer, hidden_layer, output_layer):
print("我是神经网络")
print(f"输入层有{input_layer}个神经元")
print(f"隐藏层有{hidden_layer}个神经元")
print(f"输出层有{output_layer}个神经元")
def forward(self, x):
print(f"已经接收到输入{x}")
print("正在前向传播")
class CNN(NeuralNetwork):
def __init__(self,input_layer, hidden_layer, output_layer, filters):
super().__init__(input_layer, hidden_layer, output_layer)
self.filters = filters
print(f"我是卷积神经网络,我有{self.filters}个卷积核")
def convolution(self, x):
print(f"对{x}进行卷积操作")
class RNN(NeuralNetwork):
def __init__(self, input_layer, hidden_layer, output_layer, time_steps):
super().__init__(input_layer, hidden_layer, output_layer)
self.time_steps = time_steps
print(f"我是循环神经网络,我有{self.time_steps}个时间步")
def recurrent(self, x):
print(f"对{x}进行循环操作")
input_layer = 256
hidden_layer = 128
output_layer = 10
cnn_network = CNN(input_layer, hidden_layer, output_layer, filters=32)
cnn_network.convolution(100)
rnn_network = RNN(input_layer, hidden_layer, output_layer, time_steps=5)
rnn_network.recurrent(10)