(1)
El proceso de memoria es ligeramente
(2)
class Car:
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()
self.shell.work()
class Motor:
def work(self):
print("motors' working status is alright")
class Chassis:
def work(self):
print("chassis' working status is alright")
class Seat:
def work(self):
print("seats' working status is alright")
class Shell:
def work(self):
print("shell's working status is alright")
motor = Motor()
chassis = Chassis()
seat = Seat()
shell = Shell()
car = Car(motor, chassis, seat, shell)
car.run()
(3)
class ComputerFactory:
__obj = None
__init_flag = True
def creat_computer(self, brand):
if brand == "联想":
return LianXiang()
if brand == "华硕":
return HuaShuo()
if brand == "神舟":
return ShenZhou()
else:
return "未知品牌"
def __new__(cls, *args, **kwargs):
if cls.__obj is None:
cls.__obj = object.__new__(cls)
return cls.__obj
def __init__(self):
if ComputerFactory.__init_flag:
print("init.....")
ComputerFactory.__init_flag = False
class Computer:
def __init__(self, cpu=None, screen=None):
self.cpu = cpu
self.screen = screen
def calculate(self):
print('computer运算中')
class LianXiang(Computer):
def calculate(self):
print("联想computer在计算")
def __init__(self):
Computer.__init__(self)
class HuaShuo(Computer):
def calculate(self):
print("华硕computer在计算")
def __init__(self):
Computer.__init__(self)
class ShenZhou(Computer):
def calculate(self):
print("神舟computer在计算")
def __init__(self):
Computer.__init__(self)
a1 = ComputerFactory()
a2 = ComputerFactory()
print(a1, a2)
l1 = a1.creat_computer("联想")
l1.calculate()
(4)
class Employee:
id = 1001
def __init__(self, name, salary):
self.id = Employee.id
Employee.id += 1
self.name = name
self.__salary = salary
def __add__(self, other):
if isinstance(other, Employee):
return "薪水和为{}".format(self.__salary + other.__salary)
else:
return "不是同类对象,不能相加"
@property
def salary(self):
return self.__salary
@salary.setter
def salary(self, salary):
if 1000 <= salary <= 50000:
self.__salary = salary
else:
print("工资不在要求范围内")
e1 = Employee('甘雨', 10000)
e2 = Employee('王小美', 48000)
print(e1.id, e2.id)
print(e1 + e2)
e1.set_salary = 42000
print(e1.salary)