在此代码中,有一个
Person
类,它具有属性 name
,该属性在构造对象时设置。
应该这样做:
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”
您只是将变量设置为字符串,而不是
Person
类。这将生成一个名称为 Person
的 xyz
。
some_person = Person("xyz")
您的
some_person
变量是 str
对象的实例。哪个不具有属性greeting
。
您的类
Person
应该先用 name
变量实例化,然后才能使用 greeting
:
some_person = Person(“xyz”)
print(some_person.greeting())
# "hi, my name is xyz”
#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}")
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())
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))
输出:应打印
'hi, my name is Aisha'