【问题标题】:Is there a way to catch which subclasses invoked a method of the superclass in python?有没有办法在 python 中捕获哪些子类调用了超类的方法?
【发布时间】:2015-11-27 14:55:33
【问题描述】:

我正在编写一个代码,其中有一个名为 Soft_Constr 的超类,按以下方式制作:

def __init__(self, prop, name, static_init, static_lit, pred, kind):
    init_method ...

def evaluate_clause(self):
    code here

还有一些子类可以调用超类中定义的方法“evaluate_clause”。有没有办法捕获哪些子类调用了 Soft_Constr 类中的“evaluate_clause”?

def evaluate_clause(self):
    subclasses = method_to_get_subclasses(...)

【问题讨论】:

  • self.__class__...?! – 我想谨慎地问为什么...

标签: python inheritance subclass superclass super


【解决方案1】:

这是 Python 2 的示例:

class SuperClass(object):
  def callername(self):
    print self.__class__.__name__

class ChildClass(SuperClass):
  def test(self):
    self.callername()

o = ChildClass()
o.test()

我过去经常使用它来识别用于记录目的的测试类。很有用。

对于 Python 3 并没有太大的不同:

class SuperClass():
  def callername(self):
    print(self.__class__.__name__)

class ChildClass(SuperClass):
  def test(self):
    self.callername()

o = ChildClass()
o.test()

【讨论】:

    猜你喜欢
    • 2019-11-30
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多