为什么在调用方法时会出现 AttributeError?

Why do I get an AttributeError when calling the method?

在此代码中,有一个 Person class 具有属性 name,该属性在构造对象时设置。

应该这样做:

  1. 创建 class 的实例时,属性设置正确
  2. 当调用 greeting() 方法时,问候语说明分配的名称。
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())

返回错误:

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

您只是将变量设置为字符串,而不是 Person class。这将创建一个名称为 xyzPerson

some_person = Person("xyz")

您的 some_person 变量是 str 对象的实例。没有属性 greeting.

您的 class Person 应该先用 name 变量实例化,然后才能使用 greeting:

some_person = Person(“xyz”)
print(some_person.greeting())
# "hi, my name is xyz”
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())
#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)
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}")
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}")