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

如何将Python类方法的输出写入文件?解决TypeError报错问题

解决TypeError: write() argument must be str, not None问题

问题根源

你的car_print()方法仅在控制台打印内容,没有返回任何值(Python中无return语句的函数默认返回None)。当执行file.write(my_car.car_print())时,相当于给write()传入了None,直接触发类型错误。

此外代码还有两处冗余/错误:

  • car_print里的str(print(self.year))完全无效:print()本身返回None,转字符串没有任何实际作用,应直接将self.year转为字符串参与输出。
  • 类中的get_xxx方法设计不符合规范:当前是直接打印属性,而非返回属性值,违背了getter方法的核心逻辑。

解决方案

将「生成信息字符串」和「打印信息」的逻辑拆分:新增一个方法负责生成车辆信息的字符串,car_print调用该方法完成打印;写入文件时直接调用生成字符串的方法即可。

修正后的car.py

class Car:
    def __init__(self, make, model, year, color):
        self.make = make
        self.model = model
        self.year = year
        self.color = color

    # 修正getter方法:返回属性值而非打印
    def get_make(self):
        return self.make

    def get_model(self):
        return self.model

    def get_color(self):
        return self.color

    def get_year(self):
        return self.year

    # setter方法保持不变
    def set_make(self, make):
        self.make = make

    def set_model(self, model):
        self.model = model

    def set_color(self, color):
        self.color = color

    def set_year(self, year):
        self.year = year

    # 生成车辆信息字符串
    def get_car_info(self):
        return f"{self.make}\n{self.model}\n{self.year}\n{self.color}"

    # 打印车辆信息
    def car_print(self):
        print(self.get_car_info())

    # def car_clear(self):
    #     self.make = None
    #     self.model = None
    #     self.year = None
    #     self.color = None

修正后的client.py

from car import Car

make = input("Enter the make of the car: ").capitalize()
model = input("Enter the model of the car: ").capitalize()
year = int(input("Enter the year of the car: "))
color = input("Enter the color of the car: ").capitalize()

my_car = Car(make, model, year, color)

# 控制台打印车辆信息
my_car.car_print()

# 将信息写入文件
with open('car.txt', 'w') as file:
    file.write(my_car.get_car_info())

简化方案(无需拆分逻辑)

如果不想新增方法,也可直接修改car_print让它同时完成打印和返回字符串:

def car_print(self):
    info = f"{self.make}\n{self.model}\n{self.year}\n{self.color}"
    print(info)
    return info

此时client.py中的file.write(my_car.car_print())可直接运行,既打印到控制台又写入文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:52:52