这看起来是使用类的好方法吗?

问题描述

我有一个类和一个从类中调用函数的 Python 脚本。

该类名为 User_Input_Test。该脚本名为 input_test.py

input_test.py 将使用以下类函数/方法之一请求用户输入:get_user_input(self)。然后应该通过使用称为 show_output(self) 的第二个函数/方法打印出用户输入的任何内容

它产生一个错误

User_Input_Test.show_output()\
  File "/Users/michel/Python_Projects/User_Input_Test.py",line 49,in show_output\
    """)
AttributeError: type object 'User_Input_Test' has no attribute 'brand'

看起来 show_output(self) 无法看到通过 get_user_input(self)用户那里提取的数据。

您认为这是对错误的正确解释吗?最重要的是:是否有解决方案,或者我是否试图将一个类用于它从未设计过的东西?

user_input.py

from User_Input_Test import User_Input_Test
import time

#User_Input_Test.__init__(self,name,brand,engine,doors,fuel_type,aircon,weight,mpg,tax)

print("This little application collects data about your car")
print("Please fill out the following questionnaire:")
uname = input("What is your first name?:")
User_Input_Test.get_user_input()

print(f"{uname},these are your car's attributes: ")
time.sleep(2)

User_Input_Test.show_output()

User_Input_Test.py

class User_Input_Test:
    """
    Small Class that asks the user for their car attributes and can print them out
    Attributes:
        brand(string)
        engine(string)
        ....
    """

    def __init__(self,tax):
        self.brand = brand
        self.engine = engine
        self.doors = doors
        self.fuel_type = fuel_type
        self.aircon = aircon
        self.weight = weight
        self.mpg = mpg
        self.tax = tax

    @classmethod
    def get_user_input(self):
        while 1:
            try:
                brand = input("What is the Brand & Model of your car? (e.g. 'Mercedes Benz,E-Class'):    ")
                engine = input("Engine Cylinders and displacement (e.g. '4 Cylinders,2.1 Liters'):    ")
                doors = input("How many doors does it have?:    ")
                fuel_type = input("What fuel does it use? (e.g. Petrol,Diesel,LPG):    ")
                aircon = input("Does it have Airconditioning? (Yes/No):    ")
                weight = input("How much does it weight in KG? (e.g. 1800kg):    ")
                mpg = input("What is the fuel consumption in Imperial MPG? (e.g. 38mpg):    ")
                tax = input("How much does the UK Roadtax cost per year? (e.g. £20):    ")
                return self(brand,tax)
            except:
                print('Invalid input!')
                continue
            
    def show_output(self):
        print(f"""
==========================================================================
    Brand Name:.......................  {self.brand}
    Engine:...........................  {self.engine}
    Number of Doors:..................  {self.doors}
    Fuel Type used by the engine:.....  {self.fuel_type}
    Does it have Aircon?:.............  {self.aircon}
    Fuel consumption in Imperial MPG:.  {self.mpg}
    Cost of Road Tax per Year:........  {self.tax}
==========================================================================
        """)

解决方法

User_Input_Test.show_output() 尝试在类本身上调用 show_output;您需要在 User_Input_Test.get_user_input() 返回的实例上调用它。

from User_Input_Test import User_Input_Test
import time

print("This little application collects data about your car")
print("Please fill out the following questionnaire:")
uname = input("What is your first name?:")
car = User_Input_Test.get_user_input()

print(f"{uname},these are your car's attributes: ")
time.sleep(2)

car.show_output()

注意:查看 PEP 8,Python 风格指南,特别是模块和类的命名约定。在这种情况下,我会命名模块 car 和类 Car 以便更清晰和更好的风格。此外,classmethod 的参数通常命名为 cls,因为 self 通常是为普通方法中的实例保留的。