在python中使用多态性/继承将嵌套if语句重构为类

2024-10-03 09:12:19 发布

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

在线上有几个例子,其中if...else语句被使用多态性/继承的结构替换。This link显示了一些类似于我想要实现的东西。我有一个嵌套结构,如下所示:


def wishthiswouldbeobjectoriented(figuretype, randomtype):
  if figuretype=='list':
      # do some stuff and return a list
      out = 'figure type is list'
  elif figuretype=='random':
      if randomtype=='all':
          out = 'figure type is random and randomtype is all'
      elif randomtype=='selection':
          out = 'figure type is random and randomtype is selection'
  return out

if __name__ == '__main__':
  figuretype = 'random'
  randomtype = 'selection'
  print(wishthiswouldbeobjectoriented(figuretype, randomtype))

我猜应该有一种方法可以使用多态性/继承将其转换为面向对象的代码。有没有人能在python中提供一个简短的例子来演示如何将上面的代码转换成面向对象的代码?你知道吗


Tags: and代码ifistyperandomout结构
2条回答

下面的内容纯粹是机械地使用继承作为分派方法,而不是一系列显式的if语句。这些选项不是作为参数传递给函数,而是隐式编码在类本身中。你知道吗

class Figure:
    def wishthiswouldbeobjectoriented(self):
        pass


class FigureList(Figure):
    def wishthiswouldbeobjectoriented(self):
        return "figure type is list"


class FigureRandom(Figure):
    pass


class FigureRandomAll(FigureRandom):
    def wishthiswouldbeobjectoriented(self):
        return 'figure type is random and randomtype is all'


class FigureRandomSelection(FigureRandom):
    def wishthiswouldbeobjectoriented(self):
        return 'figure type is random and randomtype is selection'


if __name__ == '__main__':
    f = FigureRandomSelection()
    print(f.wishthiswouldbeobjectoriented())

Commen: How would I from the text file know which object to instantiate,

添加以下内容:

class FigureFactory:
    def __new__(cls, args, **kwargs):
        # Mapping Type Keywords to real Class Definition
        figures = {('list',): FigureList,
                   ('random', 'all'): FigureRandomAll,
                   ('random', 'selection'): FigureRandomSelection
                   }
        figure = figures.get(args)
        if not figure:
            figure = Figure

        return figure(*kwargs['kwargs'])

扩展以下内容:

class Figure:
    ...

    @property
    def out_list(self):
        return "Invalid Type"

    def __str__(self):
        return '{} df={}'.format(self.__class__.__name__, self.df)


class FigureRandom(Figure):
    ...

    def __str__(self):
        return '{} n_value={}'.format(super().__str__(), self.n_value)

Usage: Note: Invalid Type list all!

if __name__ == '__main__':    
    ...

    for cfg in [(('list',), (df,)), 
                (('random', 'all'), (df, n_points)),
                (('random', 'selection'), (df, n_accepted + 1)), 
                (('list', 'all'), (df,))]:
        figure = FigureFactory(args=cfg[0], kwargs=cfg[1])
        print('{} {}'.format(figure, figure.out_list))

Output:

FigureList df=None figure type is list
FigureRandomAll df=None n_value=1 figure type is random and randomtype is all
FigureRandomSelection df=None n_value=2 figure type is random and randomtype is selection
Figure df=None Invalid Type

Question: refactor nested if statements into classes in python

class Figure:
    def __init__(self, df):
        self.df = df

    @property
    def out_list(self):
        return None


class FigureList(Figure):
    def __init__(self, df):
        super().__init__(df)

    @property
    def out_list(self):
        return 'figure type is list'


class FigureRandom(Figure):
    def __init__(self, df, n_value):
        super().__init__(df)
        self.n_value = n_value


class FigureRandomAll(FigureRandom):
    def __init__(self, df, n_points):
        super().__init__(df, n_points)

    @property
    def out_list(self):
        return 'figure type is random and randomtype is all'


class FigureRandomSelection(FigureRandom):
    def __init__(self, df, n_accepted):
        super().__init__(df, n_accepted)

    @property
    def out_list(self):
        return 'figure type is random and randomtype is selection'

Usage:

if __name__ == '__main__':    
    df = None
    n_points = 1
    n_accepted = 1

    for figure in [FigureList(df), FigureRandomAll(df, n_points), FigureRandomSelection(df, n_accepted)]:
        print('{}'.format(figure.out_list))

Output:

figure type is list
figure type is random and randomtype is all
figure type is random and randomtype is selection

相关问题 更多 >