0

在这段代码中,有一个Person类有一个属性name,它在构造对象时被设置。

它应该这样做:

  1. 创建类的实例时,属性被正确设置
  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”对象没有属性“greeting”

4

6 回答 6

1

您只是将变量设置为字符串,而不是Person类。这将使 aPerson的名称xyz改为。

some_person = Person("xyz")
于 2020-05-08T00:57:07.893 回答
0

您的some_person变量是str对象的一个​​实例。哪个没有属性greeting

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

some_person = Person(“xyz”)
print(some_person.greeting())
# "hi, my name is xyz”
于 2020-05-08T01:01:48.710 回答
0
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())
于 2021-01-12T04:30:10.427 回答
0
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}")
于 2021-11-22T19:02:29.180 回答
0
#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)
于 2021-09-28T11:02:30.813 回答
0
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}")
于 2022-01-20T11:27:04.753 回答