class Book(object):
def __init__(self, title):
self.title = title
def setCategory(self, category):
self.category = category
class RomanceBook(Book):
def __init__(self, title):
super(RomanceBook, self).__init__(title)
self.category = 'romance'
def getTitle(self):
return self.title.upper()
class FictionBook(Book):
def __init__(self, title):
super(FictionBook, self).__init__(title)
self.category = 'fiction'
def getTitle(self):
return self.title.lower().replace(' ', '_')
RomanceBook
和FictionBook
类都继承自同一个Book
类。这两个类都有返回书名的getTitle()
方法。RomanceBook
使用大写字母返回标题,FictionBook
类使用小写字母返回标题:
romance_book = RomanceBook('Love Story')
print romance_book, romance_book.getTitle()
fiction_book = FictionBook('Star Wars')
print fiction_book.getTitle()
这张照片:
<__main__.RomanceBook object at 0x108d37610> LOVE STORY
<__main__.FictionBook object at 0x108d37650> star_wars
现在我继续将category
实例的fiction_book
属性从'fiction'更改为romance
。你知道吗
fiction_book.setCategory('romance')
如果fiction_book
实例在更改category
属性的同时将其类从FictionBook
切换到RomanceBook
,那就太好了。它将继承RomanceBook
的所有行为,就像一本“真正的”浪漫书。如果我把它的类别改成“小说”,它就会再次改变它的类别,以此类推。你知道吗
我们如何修改示例代码使其工作?你知道吗
这应该是您想要的,通过将getTitle方法提取到基类并动态决定应该使用哪种策略:
可能有比类切换更好的方法(可能类似于strategy pattern),但是如果您真的想这样做,您可以分配给实例
__class__
:或者,如果要使用元类自动添加到
classes
:策略模式示例:
这可以在不同的变体中完成,但基本上是关于委派方法:
相关问题 更多 >
编程相关推荐