python - 继承虚拟类方法 - 如何从基类调用它?

标签 python inheritance class-method

B继承自A 。假设 B 中的一些的行为取决于类属性 cls_x我们希望在 B 的构建过程中设置这种依赖关系对象。由于这不是一个简单的操作,我们希望将其包装在一个类方法中,构造函数将调用该方法。示例:

class B(A):
  cls_x = 'B'

  @classmethod
  def cm(cls):
    return cls.cls_x

  def __init__(self):
    self.attr = B.cm()

问题:cm以及 __init__将始终做相同的事情,并且它们的行为在每个派生类中必须保持相同。因此,我们希望将它们都放在基类中,并且在任何派生类中定义它。唯一的区别是 cm 的调用者- 要么 AB (或 B1B2 中的任何一个,每个都继承自 A ),无论正在构造什么。所以我们想要的是这样的:

class A:
  cls_x = 'A'

  @classmethod
  def cm(cls):
    return cls.cls_x

  def __init__(self):
    self.attr = ClassOfWhateverIsInstantiated.cm()  #how to do this?

class B(A):
  cls_x = 'B'

我觉得这要么是我在 Python 的继承机制中遗漏了一些非常简单的东西,要么整个问题应该以完全不同的方式处理。

这与 this 不同问题是因为我不想重写类方法,而是将其实现完全移至基类。

最佳答案

这样看:您的问题本质上是“如何获取实例的类?”。该问题的答案是使用 type功能:

ClassOfWhateverIsInstantiated = type(self)

但你甚至不需要这样做,因为类方法可以直接通过实例调用:

def __init__(self):
    self.attr = self.cm()  # just use `self`

这是有效的,因为类方法会自动为您查找实例的类。来自 the docs :

[A classmethod] can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

关于python - 继承虚拟类方法 - 如何从基类调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50581979/

相关文章:

Python 字符串先进先出

c++ - 如何最好地使用抽象基类作为接口(interface)而不重复兄弟类函数重写

ruby - 将实例方法委托(delegate)给类方法

python - python 中类方法和静态变量的行为

python 自定义排序列表 1/2/3/../9/10

Python:IndexError:列表索引超出范围仅在某些情况下发生

python - 值错误: Invalid dataset identifier (invalid dataset identifier)

Java 继承 : should an extension of a class inherit the class?

css - <a> 标签何时不继承父标签的颜色属性?

python - 如何在未模拟的类中使用 autospec 修补类方法?