我的理解就是先定义一个模板父类,这是一个抽象类,含有一些抽象方法,在写若干个子类,继承这个抽象类实现这些方法。完全没有难度。
最后,实现一个类似于代理的类,用户输入什么就建立什么类。
from abc import abstractmethod, ABCMeta
# 构建一个抽象类
class Trip(metaclass=ABCMeta):
@abstractmethod
def setTransport(self):
pass
@abstractmethod
def day1(self):
pass
@abstractmethod
def day2(self):
pass
@abstractmethod
def day3(self):
pass
@abstractmethod
def returnHome(self):
pass
def itinerary(self):
self.setTransport()
self.day1()
self.day2()
self.day3()
self.returnHome()
class VeniceTrip(Trip):
def setTransport(self):
print('Take a boat and find your way in the Grand Canal')
def day1(self):
print("Visit St Mark's Basilica in St Mark's Square")
def day2(self):
print("Appreciate Doge's Palace")
def day3(self):
print('Enjoy the food near the Rialto Bridge')
def returnHome(self):
print('Get souvenirs for friends and get back')
class MaldivesTrip(Trip):
def setTransport(self):
print('On foot, on any island, Wow!')
def day1(self):
print('Enjoy the marine life of Banana Reef')
def day2(self):
print('Go for the water sports and snorkelling')
def day3(self):
print('Relax on the beach and enjoy the sun')
def returnHome(self):
print('Dont feel like leaving the beach..')
# 下面开发两个具体类:VeniceTrip 和 MaldivesTrip
class VeniceTrip(Trip):
def setTransport(self):
print('Take a boat and find your way in the Grand Canal')
def day1(self):
print("Visit St Mark's Basilica in St Mark's Square")
def day2(self):
print("Appreciate Doge's Palace")
def day3(self):
print('Enjoy the food near the Rialto Bridge')
def returnHome(self):
print('Get souvenirs for friends and get back')
class MaldivesTrip(Trip):
def setTransport(self):
print('On foot, on any island, Wow!')
def day1(self):
print('Enjoy the marine life of Banana Reef')
def day2(self):
print('Go for the water sports and snorkelling')
def day3(self):
print('Relax on the beach and enjoy the sun')
def returnHome(self):
print('Dont feel like leaving the beach..')
# 以下是Dev 旅行社以及他们如何根据客户的选择安排旅行的具体实现:
class TravelAgency:
def arrange_trip(self):
choice = input("What kind of place you'd like to go to historical or to a beach?")
if choice == 'historical':
self.trip = VeniceTrip()
self.trip.itinerary()
if choice == 'beach':
self.trip = MaldivesTrip()
self.trip.itinerary()
TravelAgency().arrange_trip()