Python Class instance object has no attribute 'undefined_method'

Question:

Class definition

class Car:
    
    amount_cars = 0
    
    def __init__(self, manufacturer, model, hp):
        self.manufacturer = manufacturer
        self.model = model
        self.hp = hp
        Car.amount_cars += 1
    
    def print_car_amount(self):
        print("Amount: {}".format(Car.amount_cars))

Creating instance

myCar1 = Car("Tesla", "Model X", 525)

Printing instance

myCar1.print_info()

Output:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [37], in <cell line: 1>()
----> 1 myCar1.print_info()

AttributeError: 'Car' object has no attribute 'print_info

Need help in finding the error

Asked By: TheBetterView

||

Answers:

As it is stated in the error message, tou have no method by the name print_info. Probably, you’re trying to do:

myCar1.print_car_amount()
Answered By: Ni3dzwi3dz
class Car:

amount_cars = 0

def __init__(self, manufacturer, model, hp):
    self.manufacturer = manufacturer
    self.model = model
    self.hp = hp
    Car.amount_cars += 1

def print_info(self): # Changed
    print("Amount: {}".format(Car.amount_cars))
Answered By: su yong kim
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.