Skip to content
Advertisement

Im confused on how to print out my fav food is cake on my console and I also keep getting an error that says ‘Person’ object has no attribute ‘Food’

class Person:
  def __init__(self,Food):
    
    def FindFood(self):
      print("my fav food is"+ self.Food)
p1 = Person("cake")
p1.FindFood()

Advertisement

Answer

You’re missing some code, and your indentation is off. First, in your class’s __init__ method, you need to assign the Food argument to the attribute self.Food. It doesn’t happen automatically.

class Person:
    def __init__(self,Food):
        self.Food = Food

Next, your method FindFood is a sibling to the __init__ method, not contained within it, so you need to unindent it one level.

class Person:
    def __init__(self,Food):
        self.Food = Food

    def FindFood(self)
        print("my fav food is "+ self.Food)

The rest of your code is correct: make an instance of your class called p1, passing the Food argument "cake". Then, call the FindFood method and it prints the result.

Note that I changed the indentation to 4 spaces, as specified in PEP 8 — The Style Guide for Python Code.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement