You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python初学者:如何在子类中设置变量

Python入门:类与子类的汽车示例学习笔记

最近刚啃到Python的类相关内容,教材用汽车/电动汽车的例子来讲解类、子类这些核心概念,特别接地气!先给大家分享下基础的Car类示例代码:

class Car():
    ''' A simple attempt to represent a car '''
    def __init__(self, make, model, year):
        ''' Initialize attributes to describe a car '''
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def car_description(self):
        ''' Return a neatly formatted descriptive name '''
        # 原代码没写完,不过核心功能是生成规整的汽车名称
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

代码要点拆解

  • __init__初始化方法:这是类的构造函数,创建Car实例时会自动触发,用来给汽车绑定品牌(make)、型号(model)、生产年份(year)这三个核心属性,还默认把里程表读数odometer_reading设为0,不用每次手动传参。
  • car_description方法:专门用来生成格式统一的汽车全称,比如把传入的2020、toyota、camry转换成2020 Toyota Camry,方便快速查看汽车基本信息。

后续还会基于这个基础类扩展ElectricCar子类,用来理解子类如何继承父类的属性和方法,再添加自己特有的属性(比如电池容量)和方法,等我学透了再来补充细节~

内容的提问来源于stack exchange,提问作者jisham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:12:28