Reputation: 27
In this code, there's a Person
class that has an attribute name
, which gets set when constructing the object.
It should do:
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'
Upvotes: 0
Views: 6955
Reputation: 1
Class Person:
def_init_(self,name):
self.name = name
def greeting(self):
return name
Some_person = Person("Aisha")
Print("hi, my name is {}".format(Some_person.name))
Output: should print 'hi, my name is Aisha'
Upvotes: 0
Reputation: 9
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.
print("hi, my name is ",self.name)
# Create a new instance with a name of your choice
some_person = Person("Honey")
# Call the greeting method
print(some_person.greeting())
Upvotes: 0
Reputation: 11
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 name
# Create a new instance with a name of your choice
some_person = Person("XYZ")
# Call the greeting method
print(f"hi, my name is {some_person.name}")
Upvotes: 0
Reputation: 1
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 name
# Create a new instance with a name of your choice
some_person = Person("Bob")
# Call the greeting method
print(f"hi, my name is {some_person.name}")
Upvotes: 0
Reputation: 1
#Use str method instead of greeting() method
def __str__(self):
# Should return "hi, my name is " followed by the name of the Person.
return "hi, my name is {}".format(self.name)
some_person = Person("xyz")
# Call the __str__ method
print(some_person)
Upvotes: 0
Reputation: 93
Your some_person
variable is an instance of str
object. Which does not have the attribute greeting
.
Your class Person
should be instanced with name
variable before you can use greeting
:
some_person = Person(“xyz”)
print(some_person.greeting())
# "hi, my name is xyz”
Upvotes: 0
Reputation: 2455
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")
Upvotes: 1