我写了这样的代码,我不明白为什么我不能像调用 show_info() 函数一样调用 full_name() 函数? 如何修复此错误(字符串对象不可调用)?
class Cake:
bakery_offer = []
def __init__(self, name, kind, taste, additives, filling):
self.name = name
self.kind = kind
self.taste = taste
self.additives = additives.copy()
self.filling = filling
self.bakery_offer.append(self)
def show_info(self):
print("{}".format(self.name.upper()))
print("Kind: {}".format(self.kind))
print("Taste: {}".format(self.taste))
if len(self.additives) > 0:
print("Additives:")
for a in self.additives:
print("\t\t{}".format(a))
if len(self.filling) > 0:
print("Filling: {}".format(self.filling))
print('-' * 20)
@property
def full_name(self):
return "--== {} - {} ==--".format(self.name.upper(), self.kind)
cake01 = Cake('Vanilla Cake', 'cake', 'vanilla', ['chocolate', 'nuts'], 'cream')
cake01.show_info()
cake01.full_name()
您将
full_name
声明为 @property
而不是常规方法,因此现在 cake.full_name
已经调用它并为您提供字符串结果,而不是通常的 cake.full_name()
。因此,额外的 ()
会导致调用字符串而不是函数。