提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
1、深拷贝浅拷贝内存图
#测试对象的引用赋值、浅拷贝、深拷贝
import copy
class MobilePhone:
def init(self,cpu,screen):
self.cpu = cpu
self.screen = screen
class CPU:
def calculate(self):
print(“计算,算个 12345”)
print(“CPU 对象:”,self)
class Screen:
def show(self):
print(“显示一个好看的画面,亮瞎你的钛合金大眼”)
print(“屏幕对象:”,self)
c = CPU()
s = Screen()
m = MobilePhone(c,s)
m.cpu.calculate()
n = m #两个变量,但是指向了同一个对象
print(m,n)
m2 = copy.copy(m) #m2 是新拷贝的另一个手机对象
print(m,m2)
m.cpu.calculate()
m2.cpu.calculate() #m2 和 m 拥有了一样的 cpu 对象和 screen 对象
m3 = copy.deepcopy(m)
m3.cpu.calculate() #m3 和 m 拥有不一样的 cpu 对象和 screen 对象
2、VehicleFactory
定义发动机类 Motor、底盘类 Chassis、座椅类 Seat,车辆外壳类 Shell,并使用组合 关系定义汽车类。其他要求如下: 定义汽车的 run()方法,里面需要调用 Motor 类的 work()方法,也需要调用座椅 类 Seat 的 work()方法,也需要调用底盘类 Chassis 的 work()方法。
# 定义 Motor 类
class Motor:
def work(self):
print("Motor is working.")
# 定义 Chassis 类
class Chassis:
def work(self):
print("Chassis is working.")
# 定义 Seat 类
class Seat:
def work(self):
print("Seat is working.")
# 定义 Shell 类
class Shell:
def __init__(self):
print("Shell is created.")
# 定义 Vehicle 类
class Vehicle:
def __init__(self, motor, chassis, seat, shell):
self.motor = motor
self.chassis = chassis
self.seat = seat
self.shell = shell
def run(self):
self.motor.work()
self.chassis.work()
self.seat.work()
# 创建各个部件的实例
motor = Motor()
chassis = Chassis()
seat = Seat()
shell = Shell()
# 创建 Vehicle 的实例
vehicle = Vehicle(motor, chassis, seat, shell)
# 调用 Vehicle 的 run 方法
vehicle.run()
3、ComputerFactory
使用工厂模式、单例模式实现如下需求: (1) 电脑工厂类 ComputerFactory 用于生产电脑 Computer。工厂类使用单例模式, 也就是说只能有一个工厂对象。 (2) 工厂类中可以生产各种品牌的电脑:联想、华硕、神舟 (3) 各种品牌的电脑使用继承实现: (4) 父类是 Computer 类,定义了 calculate 方法 (5) 各品牌电脑类需要重写父类的 calculate 方法
class Computer:#parent
def calculate(self):
pass
class LenovoComputer(Computer):
def calculate(self):
print("Lenovo computer is our product.")
class ASUSComputer(Computer):
def calculate(self):
print("ASUS computer is our product.")
class HASEEComputer(Computer):
def calculate(self):
print("HASEE computer is our product.")
class UnknownBrand(Computer):
def calculate(self):
print("Not included.")
# 工厂类
class ComputerFactory:
_instance = None
__init_flag = True
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls, *args, **kwargs)
return cls._instance
def create_computer(self, brand):
if brand.lower() == 'lenovo':
return LenovoComputer()
elif brand.lower() == 'asus':
return ASUSComputer()
elif brand.lower() == 'hasee':
return HASEEComputer()
else:
return UnknownBrand()#不带括号的话是无法去创建类的
def __init__(self):
if ComputerFactory.__init_flag:
print("init ComputerFactory...")
ComputerFactory.__init_flag = False
# 创建工厂单例
factory = ComputerFactory()
# 创建不同品牌的Computer 实例
lenovo = factory.create_computer('lenovo')
asus = factory.create_computer('asus')
hasee = factory.create_computer('hasee')
acer = factory.create_computer('acer')
lenovo.calculate()
acer.calculate()
asus.calculate()#test:brand not included
4、add
定义一个 Employee 雇员类,要求如下: (1) 属性有:id、name、salary (2) 运算符重载+:实现两个对象相加时,默认返回他们的薪水和 (3) 构造方法要求:输入 name、salary,不输入 id。id 采用自增的方式,从 1000 开 始自增,第一个新增对象是 1001,第二个新增对象是 1002。 (4) 根据 salary 属性,使用@property 设置属性的 get 和 set 方法。set 方法要求输 入:1000-50000 范围的数字。
class Employee:
_id_counter = 1000 # Class variable to keep track of IDs
def __init__(self, name, salary):
self.id = Employee._id_counter#实例属性self.id
Employee._id_counter += 1
self.name = name
self._salary = salary
@property#定义 salary 方法,使其在访问时看起来像属性(例如,employee.salary 而不是 employee.salary())。
def salary(self):
return self._salary#使用 @property 定义的 salary 方法使得 salary 属性变为只读属性,仅通过 self._salary 访问和返回内部存储的工资值
@salary.setter
def salary(self, value):
if not isinstance(value, int):
raise ValueError("Salary must be an integer.")
if value < 1000 or value > 50000:
raise ValueError("Salary must be between 1000 and 50000.")
self._salary = value
def __add__(self, other):#__add__ 是 Python 中的魔术方法(Magic Method),用于定义对象使用 + 操作符时的行为
if not isinstance(other, Employee):
raise ValueError("Can only add Employee instances.")
return Employee("Total", self.salary + other.salary) # 返回一个新的 Employee 对象,名字为 "Total"
def __str__(self):#__str__ 是 Python 中的魔术方法,用于定义对象在使用 print() 函数或 str() 函数时的字符串表示形式。通过重载 __str__ 方法,可以自定义对象的打印输出格式。
return "Employee(ID: {}, Name: {}, Salary: {})".format(self.id, self.name, self.salary)
@staticmethod
def total_salary(employees):
return sum(employee.salary for employee in employees)
employees=[
Employee("张三", 6000),
Employee("李四", 5500),
Employee("王五", 5500),
]
#print(employees)会打印出三个地址
for person in employees:#临时变量person,代表employees这个列表中的各元素
print(person)
total_employee = employees[0]
for emp in employees[1:]:#在for循环中临时定义变量emp。emp不需要在循环外赋值
total_employee += emp
print(f"Total Salary: {total_employee.salary}")