【Python】类与对象

简介: 【Python】类与对象

2fe19ddce53248e287f29e844d3bf607.png

一、写在前面✨


大家好!我是初心,希望我们一路走来能坚守初心!

今天跟大家分享的文章是 Python中面向对象编程的类与对象。 ,希望能帮助到大家!本篇文章收录于 初心Python从入门到精通 专栏。


🏠 个人主页:初心%个人主页

🧑 个人简介:大家好,我是初心,和大家共同努力

💕欢迎大家:这里是CSDN,我记录知识的地方,喜欢的话请三连,有问题请私信😘

💕 长大后就忘了吗?曾经拥有的梦想。』—— 藤子不二雄「哆啦A梦」


二、类与对象简介


Python 是一种面向对象的编程语言。

Python 中的几乎所有东西都是对象,拥有属性和方法。

类(Class)类似对象构造函数,或者是用于创建对象的“蓝图”。

如需创建类,请使用 class 关键字:(例如)

class MyClass:
  x = 5


  • init() 函数

上面的例子是最简单形式的类和对象,在实际应用程序中并不真正有用。

要理解类的含义,我们必须先了解内置的 init() 函数。

所有类都有一个名为 init() 的函数,它始终在启动类时执行。

类定义不能为空,但是如果您处于某种原因写了无内容的类定义语句,请使用 pass 语句来避免错误。


三、Car类的实现


编程要求:按注释要求完成下列car类的实现。

class Car:
    '''
    >>> deneros_car = Car('Tesla', 'Model S')
    >>> deneros_car.model
    'Model S'
    >>> deneros_car.gas
    30
    >>> deneros_car.gas -= 20 # The car is leaking gas
    >>> deneros_car.gas
    10
    >>> deneros_car.drive()
    'Tesla Model S goes vroom!'
    >>> deneros_car.drive()
    'Cannot drive!'
    >>> deneros_car.fill_gas()
    'Gas level: 20'
    >>> deneros_car.gas
    20
    >>> Car.gas
    30
    >>> Car.gas = 50 # Car manufacturer upgrades their cars to start with more gas
    >>> ashleys_car = Car('Honda', 'HR-V')
    >>> ashleys_car.gas
    50
    >>> ashleys_car.pop_tire()
    >>> ashleys_car.wheels
    3
    >>> ashleys_car.drive()
    'Cannot drive!'
    >>> brandons_car = Car('Audi', 'A5')
    >>> brandons_car.wheels = 2
    >>> brandons_car.wheels
    2
    >>> Car.num_wheels
    4
    >>> brandons_car.drive() # Type Error if an error occurs and Nothing if nothing is displayed
    'Cannot drive!'
    >>> Car.drive(brandons_car) # Type Error if an error occurs and Nothing if nothing is displayed
    'Cannot drive!'
    >>> brandons_car.color
    'No color yet. You need to paint me.'
    >>> brandons_car.paint('yellow')
    'Audi A5 is now yellow'
    '''
    def __init__(self, make, model):
    def paint(self, color):
    def drive(self):
    def pop_tire(self):
    def fill_gas(self):
  # Edit Your Code Here
import doctest
doctest.testmod()


具体实现:

# 定义类变量 gas 初始值为30
gas = 30
# 定义车轮初始数为4
wheels = 4
num_wheels = 4
# 初始化车品牌和车型
def __init__(self, make, model):
    self.make = make
    self.model = model
    self.color = 'No color yet. You need to paint me.'
def paint(self, color):
    self.color = color
    return self.make+' '+self.model+' is now %s'%self.color
def drive(self):
    if (self.gas > 0 and self.wheels == self.num_wheels):
        # 每次开车耗油10
        self.gas -= 10
        return 'Tesla Model S goes vroom!'
    else:
            # 如果油量不足或者车轮数不足都不能开车
        return 'Cannot drive!'
def pop_tire(self):
    # 将轮胎数减少1
    self.wheels -= 1
def fill_gas(self):
    # 加油一次加20,返回剩余油量
    self.gas += 20
    return 'Gas level: %d' % self.gas


四、Date类的实现

编程要求:date类实现年月日的-、+、==、repr方法。

class MyDate:
    """
    >>> MyDate(2023, 5, 4) == MyDate(2023, 5, 4)
    True
    >>> MyDate(2023, 5, 7) - MyDate(2023, 1, 4)
    123
    >>> MyDate(2024, 2, 29) + 365
    MyDate(2025, 2, 28)
    >>> MyDate(2025, 2, 28) - MyDate(2024, 2, 29)
    365
    >>> MyDate(2024, 12, 31) + 2
    MyDate(2025, 1, 2)
    """
    # Edit Your Code Here
    def __init__(self, year, month, day):
    def __add__(self, numofdays):
    def __sub__(self, other):
    def __eq__(self, other):
    def __repr__(self):
import doctest
doctest.testmod()

具体实现:

# 日期转换工具
from dateutil import parser
# 日期时间库
from datetime import timedelta, datetime
class MyDate:
    def __init__(self, year, month, day):
        # 判断月、日是否小于10,如果小于10就加上'0'
        if (month < 10):
            month = '0' + str(month)
        else:
            month = str(month)
        if (day < 10):
            day = '0' + str(day)
        else:
            day = str(day)
        year = str(year)
        # 将日期格式确定为'xxxx-xx-xx'
        self.date = year + '-' + month + '-' + day
    def __add__(self, numofdays):
        # 将字符串格式的日期转换为 datetime 类型
        date_obj = datetime.strptime(self.date, '%Y-%m-%d').date()
        # 加上 days 得到 新的 datetime 对象
        date = date_obj + timedelta(days=numofdays)
        # 返回新的 MyDate 对象
        return MyDate(date.year, date.month, date.day)
    def __sub__(self, other):
        # 得到相差的天数
        days = (parser.parse(self.date) - parser.parse(other.date)).days
        return days
    def __eq__(self, other):
        if isinstance(other, MyDate):
            if self.date == other.date:
                return True
            else:
                return False
    def __repr__(self):
        # 返回字符串
        date_obj = datetime.strptime(self.date, '%Y-%m-%d').date()
        return "MyDate(%d, %d, %d)"%(date_obj.year,date_obj.month,date_obj.day)


五、总结撒花😊


本文主要讲解了Python中基础的面向对象编程。😊

这就是今天要分享给大家的全部内容了,我们下期再见!😊

🏠 本文由初心原创,首发于CSDN博客, 博客主页:初心%🏠

🏠 我在CSDN等你哦!😍

相关文章
|
3天前
|
Python
Python 一步一步教你用pyglet制作可播放音乐的扬声器类
Python 一步一步教你用pyglet制作可播放音乐的扬声器类
14 0
|
10天前
|
Python
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
52 0
|
10天前
|
索引 Python
python 格式化、set类型和class类基础知识练习(上)
python 格式化、set类型和class类基础知识练习
33 0
|
11天前
|
Python
python学习12-类对象和实例对象
python学习12-类对象和实例对象
|
1月前
|
Python
Python类(class)中self的理解
Python类(class)中self的理解
19 0
|
1月前
|
Python
Python类定义:从小白到专家的旅程
Python类定义:从小白到专家的旅程
8 0
|
1月前
|
Python
Python类与对象:深入解析与应用
本文介绍了Python中的核心概念——类和对象,以及它们在面向对象编程中的应用。类是用户定义的类型,描述具有相同属性和行为的对象集合;对象是类的实例,具备类的属性和方法。文章通过示例讲解了如何定义类、创建及使用对象,包括`__init__`方法、属性访问和方法调用。此外,还阐述了类的继承,允许子类继承父类的属性和方法并进行扩展。掌握这些概念有助于提升Python编程的效率和灵活性。
|
1月前
|
机器学习/深度学习 设计模式 开发者
python类用法(四)
python类用法(四)
18 0
|
1月前
|
开发者 Python
Python对象和类
Python对象和类
11 0
|
Python 容器
【Python零基础入门篇 · 20】:可迭代对象和迭代器的转换、自定义迭代器类、异常类、生成器
【Python零基础入门篇 · 20】:可迭代对象和迭代器的转换、自定义迭代器类、异常类、生成器
104 0
【Python零基础入门篇 · 20】:可迭代对象和迭代器的转换、自定义迭代器类、异常类、生成器