Search code examples
pythonattributeerrorpython-class

Why do I get an AttributeError when calling the method?


In this code, there's a Person class that has an attribute name, which gets set when constructing the object.

It should do:

  1. When an instance of the class is created, the attribute gets set correctly
  2. When the greeting() method is called, the greeting states the assigned name.
class Person:
    def __init__(self, name):
        self.name = name
    def greeting(self):
        # Should return "hi, my name is " followed by the name of the Person.
        return "hi, my name is {}".format(self.name) 
    
# Create a new instance with a name of your choice
some_person = "xyz"  
# Call the greeting method
print(some_person.greeting())

It returned the error:

AttributeError: 'str' object has no attribute 'greeting'


Solution

  • You're just setting the variable to a string, not a Person class. This would make a Person with a name of xyz instead.

    some_person = Person("xyz")