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

2024-04-19 19:16:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类和一个调用该类函数的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, brand, engine, doors, fuel_type, aircon, weight, mpg, 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,engine,doors,fuel_type,aircon,weight,mpg,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}
==========================================================================
        """)

1条回答
网友
1楼 · 发布于 2024-04-19 19:16:06

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在常规方法中是为实例保留的

相关问题 更多 >