我可以在Python中为继承的方法创建别名吗?

时间:2016-11-16 01:48:12

标签: python python-3.x methods alias python-decorators

我的Python程序中有一个非常复杂的类层次结构。该程序有许多工具,可以是模拟器或编译器。两种方法共享一些方法,因此有一个Shared类作为所有类的基类。一个简化示例如下所示:

class Shared:
  __TOOL__ = None

  def _Prepare(self):
    print("Preparing {0}".format(self.__TOOL__))


class Compiler(Shared):
  def _Prepare(self):
    print("do stuff 1")
    super()._Prepare()
    print("do stuff 2")

  def _PrepareCompiler(self):
    print("do stuff 3")
    self._Prepare()
    print("do stuff 4")


class Simulator(Shared):
  def _PrepareSimulator(self):   # <=== how to create an alias here?
    self._Prepare()           


class Tool1(Simulator):
  __TOOL__ = "Tool1"

  def __init__(self):
    self._PrepareSimulator()

  def _PrepareSimulator(self):
    print("do stuff a")
    super()._PrepareSimulator()
    print("do stuff b")

我可以将方法Simulator._PrepareSimulator定义为Simulator/Shared._Prepare的别名吗?

我知道我可以创建像__str__ = __repr__这样的本地别名,但在我的情况下,_Prepare在上下文中是未知的。我没有self也没有cls来引用此方法。

我可以写一个装饰器来返回_Prepare而不是_PrepareSimulator吗?但是如何在装饰器中找到_Prepare

我是否也需要调整方法绑定?

1 个答案:

答案 0 :(得分:1)

我设法创建了一个基于装饰的解决方案,确保了类型的安全性。第一个装饰器注释本地方法的别名。需要保护别名目标。需要第二个装饰器来替换Alias实例,并检查别名是否指向类型层次结构中的方法。

装饰者/别名定义:

from inspect import getmro

class Alias:
  def __init__(self, method):
    self.method = method

  def __call__(self, func):
    return self

def HasAliases(cls):
  def _inspect(memberName, target):
    for base in getmro(cls):
      if target.__name__ in base.__dict__:
        if (target is base.__dict__[target.__name__]):
          setattr(cls, memberName, target)
          return
      else:
        raise NameError("Alias references a method '{0}', which is not part of the class hierarchy: {1}.".format(
          target.__name__, " -> ".join([base.__name__ for base in getmro(cls)])
        ))

  for memberName, alias in cls.__dict__.items():
    if isinstance(alias, Alias):
      _inspect(memberName, alias.method)

  return cls

用法示例:

class Shared:
  __TOOL__ = None

  def _Prepare(self):
    print("Preparing {0}".format(self.__TOOL__))


class Shared2:
  __TOOL__ = None

  def _Prepare(self):
    print("Preparing {0}".format(self.__TOOL__))


class Compiler(Shared):
  def _Prepare(self):
    print("do stuff 1")
    super()._Prepare()
    print("do stuff 2")

  def _PrepareCompiler(self):
    print("do stuff 3")
    self._Prepare()
    print("do stuff 4")


@HasAliases
class Simulator(Shared):
  @Alias(Shared._Prepare)
  def _PrepareSimulatorForLinux(self):    pass

  @Alias(Shared._Prepare)
  def _PrepareSimulatorForWindows(self):  pass


class Tool1(Simulator):
  __TOOL__ = "Tool1"

  def __init__(self):
    self._PrepareSimulator()

  def _PrepareSimulator(self):
    print("do stuff a")
    super()._PrepareSimulatorForLinux()
    print("do stuff b")
    super()._PrepareSimulatorForWindows()
    print("do stuff c")

t = Tool1()

@Alias(Shared._Prepare)设置为@Alias(Shared2._Prepare)会引发异常:

  

NameError:Alias引用方法'_Prepare',它不是类层次结构的一部分:Simulator - &gt;共享 - &gt;对象