字符串对象不可调用" Python对象编程问题
我写了这样的代码,但我不明白为什么我不能像调用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()
1 个回答
2
你把 full_name
声明成了 @property
,而不是普通的方法,所以现在当你用 cake01.full_name
时,它会直接调用这个属性,并返回你函数的结果字符串。这样就不需要像平常那样写成 cake01.full_name()
,因为有了 @property
的话,后面就不用加括号了。多加的 ()
会导致你调用的是字符串,而不是一个函数。
这和 cake01.show_info()
不一样,因为在那种情况下你没有使用 @property
。
正确使用你的属性的方法是:
print(cake01.full_name)