继续获取'RestaurantReview'对象没有属性'_RestaurantReview__name'但似乎我已将所有内容传递到ReviewRestaurant中的ReviewRestaurant
class Review:
def __init__(self, nm, dt, strs):
self.__name = nm
self.__date = dt
self.__stars = strs
def set_name(self, name):
self.__name = name
def set_date(self, date):
self.__date = date
def set_stars(self,stars):
self.__stars = stars
def get_name(self):
return self.__name
def get_date(self):
return self.__date
def get_stars(self):
return self.__stars
def __str__(self):
return 'RESTAURANT: ' + 'Name: ' + str(self.__name) + 'Date: ' + str(self.__date) + 'Number of stars: ' + str(self.__stars)
class RestaurantReview:
def __init__(self, nm, dt, strs, csne):
Review.__init__(self, nm, dt, strs)
self.__cuisine = csne
def set_cuisine(self, cuisine):
self.__cuisine = cuisine
def get_cuisine(self):
return self.__cuisine
def __str__(self):
return 'RESTAURANT: ' + 'Name: ' + str(self.__name) + 'Date: ' + str(self.__date) + 'Number of stars: ' + str(self.__stars) + 'Cuisine' + str(self.__cuisine)
def main():
r2 = RestaurantReview('Red Robin', '5-3-18', 4, 'Burgers')
print(r2)
main()
答案 0 :(得分:0)
您需要将RestaurantReview声明为Review的子类:
class Review:
def __init__(self, nm, dt, strs):
self.__name = nm
self.__date = dt
self.__stars = strs
def __str__(self):
return 'RESTAURANT: ' + 'Name: ' + str(self.name) + 'Date: ' + str(self.date) + 'Number of stars: ' + str(self.stars)
@property
def name(self):
return self.__name
@property
def date(self):
return self.__date
@property
def stars(self):
return self.__stars
class RestaurantReview(Review):
def __init__(self, nm, dt, strs, csne):
super(RestaurantReview, self).__init__(nm, dt, strs)
self.__cuisine = csne
@property
def cuisine(self):
return self.__cuisine
def __str__(self):
return 'RESTAURANT: ' + 'Name: ' + str(self.name) + 'Date: ' + str(self.date) + 'Number of stars: ' + str(self.stars) + 'Cuisine' + str(self.cuisine)
def main():
r2 = RestaurantReview('Red Robin', '5-3-18', 4, 'Burgers')
print(r2)
main()
您不需要对属性进行私有化,否则您必须创建getter方法来访问每个私有属性。
编辑:我将属性保留为私有,并添加属性以获取其值。