面向对象2

这篇博客探讨了面向对象编程中的类定义,包括Car、Motor、Seat、Chassis和Shell类的实现。同时,展示了工厂模式的应用,通过ComputerFactory类创建不同品牌的计算机,如华硕、联想和神州,并且每个品牌电脑的计算方法有所不同。此外,还涉及了Employee类的设计,包含员工ID、姓名和薪资属性,实现了加薪操作和薪资的getter、setter方法。
摘要由CSDN通过智能技术生成

作业1

在这里插入图片描述

作业2

// An highlighted block
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.seat.work()
        self.chassis.work()


class Motor:
    def work(self):
        print("Motor is work.")


class Seat:
    def work(self):
        print("seat is work...")


class Chassis:
    def work(self):
        print("chasis is work...")


class shell:
    pass

作业3

// An highlighted block
class ComputerFactory:
    __obj = None
    __init_flag = True

    def create_car(self, brand):
        if brand == '华硕':
            return Huashuo()
        elif brand == '联想':
            return Lianxiang()
        elif brand == '神州':
            return Shenzhou()
        else:
            return "未知品牌无法创建"

    def __new__(cls, *args, **kwargs):
        if cls.__obj == None:
            cls.__obj = object.__new__()
        return cls.__obj

    def __init__(self):
        if ComputerFactory.__init_flag:
            print("init computerfactory")
            ComputerFactory.__init_flag = False

class Computer:
    def calculate(self):
        print("calculate computer")

class Lianxiang(Computer):
    def calculate(self):
        print("calculate Lianxiang")


class Huashuo(Computer):
    def calculate(self):
        print("calculate Huashuo")


class Shenzhou(Computer):
    def calculate(self):
        print("calculate Shenzhou")

作业4

// An highlighted block
class Employee:
    id = 1000

    def __init__(self, name, salary):

        self.id = Employee.id + 1
        self.name = name
        self.__salary = salary
        Employee.id += 1

    def __add__(self, other):
        if isinstance(other, Employee):
            return other.salary + self.salary

    @property
    def salary(self):
        print("salary is {0}".format(self.__salary))

    @salary.setter
    def salary(self, salary):
        if (1000 < salary < 50000):
            self.__salary = salary
        else:
            print("input again")


e1 = Employee("a", 3000)
e2 = Employee("b", 2000)
e3 = Employee("b", 4000)
e3.salary = 5000
print(e1.id)
print(e2.id)
print(e3.id)
print(e3.salary)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值