【问题标题】:python2.7: Is it possible to determine whether __init__ was called from a subclass or just normally?python2.7:是否可以确定 __init__ 是从子类调用还是正常调用?
【发布时间】:2019-04-03 10:32:10
【问题描述】:

我有两节课

class A()

class B(A)

有时A类被正常实例化,有时通过B类实例化

super(B, self).__init__()

能否判断A类的init方法是从B调用还是从外部调用?

【问题讨论】:

  • 你可以测试self是否是B的实例。这通常表明您正在处理错误的事情。
  • 为什么重要?
  • 这不应该是班级A的事...

标签: python class subclass super


【解决方案1】:

您可以将type(self)A 进行比较:

class A(object):

    def __init__(self):
        if type(self) == A:
            print('From A')

        else:
            print('From elsewhere')

class B(A):
    pass

A()
B()

输出:

From A
From elsewhere

这是您希望 type 超过 isinstance 的唯一一次,尽管我不确定为什么您首先要这样做。

【讨论】:

  • 我想将它们添加到列表中,并且打算在构造函数中进行,但如果不添加超类,则只想添加子类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-05
  • 2013-12-05
  • 2023-03-14
  • 2013-02-22
  • 2020-07-06
  • 1970-01-01
相关资源
最近更新 更多