## class restaurant ##
实现超类
class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print('This restaurant is called ' + self.restaurant_name + '.')
print('This restaurant serves dishes acoording to ' + self.cuisine_type + '.')
def open_restaurant(self, hours):
self.hours = hours
print(self.restaurant_name.title() + ' is opened ' + str(hours) + '!')
class IceCreamStand(Restaurant):
def __init__(self, restaurant_name, cuisine_type):
super().__init__(restaurant_name, cuisine_type)
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
flavours = ['chocolate', 'vanilia', 'strawberry', 'lime', 'orange']
def flavours(self):
print('Available flavours: ')
for flavour in flavours:
print(flavour)
IceCreamStand = Restaurant(' Matt IceCream ', 'ice creams')
IceCreamStand.describe_restaurant()
IceCreamStand.flavours()
因为
Restaurant
确实没有属性flavours
; IceCreamStand
会,或者至少会,直到您用 Restaurant
的实例替换该类并使用 IceCreamStand = Restaurant(...)
。
使用不同的变量名称(类名采用驼峰式命名,对象采用首字母小写的蛇形命名法),并创建
IceCreamStand
的实例。
ice_cream_stand = IceCreamStand(' Matt IceCream ', 'ice creams')
关闭此循环,以防其他初学者试图理解 Python 中 OOP 的属性错误/按数量级解决这些错误:
super().__init__
之外实例化,因为这会将它们传递给 __init__
方法) Restaurant 类,并使其可以在 IceCreamStand 类中访问)__init__
方法时)请参阅下面的更改/运行代码:
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print('This restaurant is called ' + self.restaurant_name + '.')
print('This restaurant serves dishes acoording to ' + self.cuisine_type + '.')
def open_restaurant(self, hours):
print(self.restaurant_name.title() + ' is opened ' + str(hours) + '!')
class IceCreamStand(Restaurant):
def __init__(self, restaurant_name, cuisine_type):
super().__init__(restaurant_name, cuisine_type)
self.flavours = ['chocolate', 'vanilia', 'strawberry','lime', 'orange']
def flavours(self):
print('Available flavours: ')
for flavour in self.flavours:
print(flavour)
stand = IceCreamStand(' Matt IceCream ', 'ice creams')
stand.describe_restaurant()
stand.flavours()