如何轉換課程

2024-09-30 04:26:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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(' ', '_')

RomanceBookFictionBook类都继承自同一个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的所有行为,就像一本“真正的”浪漫书。如果我把它的类别改成“小说”,它就会再次改变它的类别,以此类推。你知道吗

我们如何修改示例代码使其工作?你知道吗


Tags: selfobjecttitleinitdefclasscategoryfiction
3条回答

这应该是您想要的,通过将getTitle方法提取到基类并动态决定应该使用哪种策略:

class Book(object):
    def __init__(self, title):
        self.title = title

    def setCategory(self, category):
        self.category = category

    def getTitle(self):

        if self.category == 'romance':
            return self.title.upper()
        elif self.category == 'fiction':
            return self.title.lower().replace(' ', '_')
        else:
            raise NotImplementedError()


class RomanceBook(Book):
    def __init__(self, title):
        super(RomanceBook, self).__init__(title)
        self.category = 'romance'


class FictionBook(Book):
    def __init__(self, title):
        super(FictionBook, self).__init__(title)
        self.category = 'fiction'


romance_book = RomanceBook('Love Story')
print(romance_book.getTitle())

fiction_book = FictionBook('Star Wars')

print(fiction_book.getTitle())

fiction_book.setCategory('romance')

print(fiction_book.getTitle())

可能有比类切换更好的方法(可能类似于strategy pattern),但是如果您真的想这样做,您可以分配给实例__class__

class Book(object):
    def __init__(self, title):
        self.title = title

    def setCategory(self, category):
        self.category = category
        self.__class__ = classes[category] # IMPORTANT


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(' ', '_')

classes = {
  'romance': RomanceBook, # IMPORTANT
  'fiction': FictionBook, # IMPORTANT
}

或者,如果要使用元类自动添加到classes

classes = {}

class BookMetaclass(type):
  def __new__(cls, name, bases, attrs):
          new_class = type.__new__(cls, name, bases, attrs)
          if name != "Book":
            classes[new_class.category] = new_class

          return new_class

class Book(object, metaclass=BookMetaclass):
    def __init__(self, title):
        self.title = title

    def setCategory(self, category):
        self.category = category
        self.__class__ = classes[category]

...

策略模式示例:

class Book(object):
    title_funcs = {
      'romance': lambda title: title.upper(),
      'fiction': lambda title: title.lower().replace(' ', '_'),
    }

    def __init__(self, category, title):
        self.category = category
        self.title = title

    def setCategory(self, category):
        self.category = category

    def getTitle(self):
      return self.title_funcs[self.category](self.title)

这可以在不同的变体中完成,但基本上是关于委派方法:

class RomanceBookSupport:

    @staticmethod
    def getTitle(book):
        return book.title.upper()


class FictionBookSupport:

    @staticmethod
    def getTitle(book):
        return book.title.lower().replace(' ', '_')


SUPPORTMAP = {
    'romance' : RomanceBookSupport,
    'fiction' : FictionBookSupport
}


class Book(object):
    def __init__(self, title):
        self.title = title

    def setCategory(self, category):
        self.category = category

    def getTitle(self):
        return SUPPORTMAP[self.category].getTitle(self)


romance_book = Book('Love Story')
romance_book.setCategory('romance')
print romance_book, romance_book.getTitle() 

fiction_book = Book('Star Wars')
fiction_book.setCategory('fiction')
print fiction_book.getTitle()

fiction_book.setCategory('romance')
print fiction_book.getTitle()

相关问题 更多 >

    热门问题