如何将类方法的输出写入Python中的文件?

huangapple go评论77阅读模式
英文:

How can I write the output of a class method to a file in Python?

问题

I've been following Python tutorials on YouTube for the past couple of days now, and have made it to an OOP section. The example code has two modules, client.py and car.py. Within car.py is a class called Car, with attributes for the make, model, color (all strings), and year (integer). I decided to expand on the example code to challenge myself and implemented a method called car_print which prints the aforementioned information to the console, but as of right now it isn't working.

I'm trying to write the results of car_print to a file "car.txt" in my main module, but am getting the following error: file.write(my_car.car_print()), TypeError: write() argument must be str, not None, where my_car is an object of class Car. The only place my code contains None is within car_clear, a method designed to reset the Car object to an empty state where each attribute is set to None. car_print works as expected when called; the issue only arises when trying to write the output to a file.

Here are the contents of 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)

with open('car.txt', 'w') as file:
    file.write(my_car.car_print())

as well as car.py:

class Car:
    # Class constructor-------------------------------------------------------------------------
    def __init__(self, make, model, year, color):
        self.make = make
        self.model = model
        self.year = year
        self.color = color

    # Access functions--------------------------------------------------------------------------
    def get_make(self):  # returns make
        print(self.make)

    def get_model(self):  # returns model
        print(self.model)

    def get_color(self):  # returns color
        print(self.color)

    def get_year(self):  # returns year
        print(str(self.year))

    # Manipulation procedures-------------------------------------------------------------------
    def set_make(self, make):  # overwrites self.make with make
        self.make = make

    def set_model(self, model):  # overwrites self.model with model
        self.model = model

    def set_color(self, color):  # overwrites self.color with color
        self.color = color

    def set_year(self, year):  # overwrites self.year with year
        self.year = year

    # Other functions---------------------------------------------------------------------------
    def car_print(self):  # prints all attributes of car object
        print(self.make)
        print(self.model)
        str(print(self.year))
        print(self.color)

    # def car_clear(self):  # resets car object to empty state
    #     self.make = None
    #     self.model = None
    #     self.year = None
    #     self.color = None

英文:

I've been following Python tutorials on YouTube for the past couple of days now, and have made it to an OOP section. The example code has two modules, client.py and car.py. Within car.py is a class called Car, with attributes for the make, model, color (all strings), and year (integer). I decided to expand on the example code to challenge myself and implemented a method called car_print which prints the aforementioned information to the console, but as of right now it isn't working.

I'm trying to write the results of car_print to a file "car.txt" in my main module, but am getting the following error: file.write(my_car.car_print()), TypeError: write() argument must be str, not None, where my_car is an object of class Car. The only place my code contains None is within car_clear, a method designed to reset the Car object to an empty state where each attribute is set to None. car_print works as expected when called; the issue only arises when trying to write the output to a file.

Here are the contents of 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)

with open('car.txt', 'w') as file:
    file.write(my_car.car_print())

as well as car.py:

class Car:
    # Class constructor-------------------------------------------------------------------------
    def __init__(self, make, model, year, color):
        self.make = make
        self.model = model
        self.year = year
        self.color = color

    # Access functions--------------------------------------------------------------------------
    def get_make(self):  # returns make
        print(self.make)

    def get_model(self):  # returns model
        print(self.model)

    def get_color(self):  # returns color
        print(self.color)

    def get_year(self):  # returns year
        print(str(self.year))

    # Manipulation procedures-------------------------------------------------------------------
    def set_make(self, make):  # overwrites self.make with make
        self.make = make

    def set_model(self, model):  # overwrites self.model with model
        self.model = model

    def set_color(self, color):  # overwrites self.color with color
        self.color = color

    def set_year(self, year):  # overwrites self.year with year
        self.year = year

    # Other functions---------------------------------------------------------------------------
    def car_print(self):  # prints all attributes of car object
        print(self.make)
        print(self.model)
        str(print(self.year))
        print(self.color)

    # def car_clear(self):  # resets car object to empty state
    #     self.make = None
    #     self.model = None
    #     self.year = None
    #     self.color = None

答案1

得分: 2

请注意,如果你想将内容写入文件,该方法需要返回一个值。

由于你使用了

def car_print(self):  # 打印汽车对象的所有属性
    print(self.make)
    print(self.model)
    str(print(self.year))
    print(self.color)

该方法没有返回值,而是将参数打印到标准输出流(在这种情况下是控制台)。

为了将变量传递给write()函数,你需要在方法中使用return关键字。最简单的版本是:

def car_print(self):  # 打印汽车对象的所有属性
    return self.make + self.model + self.year + self.color

当然,你可以在值之间添加一些描述:

def car_print(self):  # 打印汽车对象的所有属性
    return '制造商: ' + self.make + ' 型号: ' + self.model + ' 年份: ' + self.year + ' 颜色: ' + self.color

更优雅的版本是使用字符串格式化,在开头引号前添加一个f,然后在{}内写入要包含的值:

def car_print(self):  # 打印汽车对象的所有属性
    return f'制造商: {self.make} 型号: {self.model} 年份: {self.year} 颜色: {self.color}'

有多种格式化字符串的方式,给出的只是其中之一。

英文:

Note that if you want to write something to a file, the method needs to return a value.

Since you used

  def car_print(self):  # prints all attributes of car object
        print(self.make)
        print(self.model)
        str(print(self.year))
        print(self.color)

the method doesn't return a value, instead just prints the arguments to the standard output stream (in this case the console).

In order to pass the variables to the write() function, you need to use the return keyword in the method. The simplest version:

def car_print(self):  # prints all attributes of car object
    return self.make + self.model + self.year + self.color

Of course you could add some description in between the values:

def car_print(self):  # prints all attributes of car object
    return 'Make: ' + self.make + ' Model: ' + self.model + ' Year: ' + self.year + ' Color: ' + self.color

A more elegant version is to use string formatting by adding an f before the opening quotation and then write the values you want to include within {}:

def car_print(self):  # prints all attributes of car object
    return f'Make: {self.make} Model: {self.model} Year: {self.year} Color: {self.color}'

There is multiple ways to format strings, the given one is but one of them.

答案2

得分: 1

当在Python中使用print()函数时,实际上将输出内容打印到终端。为了使用file.write(string)函数,您必须从函数中返回一个字符串。您的新代码应该类似于以下内容:

def get_make(self):  # 返回制造商
    return self.make

现在,字符串将通过return关键字传递给file.write()

对于您的较大的car_print()函数,您需要将不同的变量相加,我喜欢使用f字符串来做到这一点。代码可能如下所示:

def car_print(self):  # 打印汽车对象的所有属性
    return f"{self.make}, {self.model}, {self.year}, {self.color}"
英文:

When using the print() function in python you actually print that output to the terminal. In order to use the 'file.write(string)' function you must return a string from the function. Your new code should look a bit like this:

def get_make(self):  # returns make
        return self.make

Now the string will get passed to the file.write() by the return keyword.

For your larger car_print() function you will need to add the different variables together, I like f strings to do this. It would look something like this:

def car_print(self):  # prints all attributes of car object
        return f"{self.make}, {self.model}, {self.year}, {self.color}"

huangapple
  • 本文由 发表于 2023年6月19日 15:01:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76504303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定