派生类未在\u init中运行代码_

2024-09-28 22:31:53 发布

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

为什么下面的代码不打印"Hello"?你知道吗

# C derives from B, which derives from A, which derives from object
class D(C):
  def _init_(self, *args, **kw):
    print "Hello"


foo = D('some_text')

我已经在Python2.7中测试过了,但没有成功。你知道吗

我没有包括CBA的代码,但这又有什么关系呢?你知道吗

我很高兴包含它们的定义,但我不想不必要地使上面的代码复杂化。你知道吗


Tags: 代码fromselfhellowhichobjectfooinit
2条回答
# C derives from B, which derives from A, which derives from object
class D(C):
  def __init__(self, *args, **kw):
    print "Hello"


foo = D('some_text')

双下划线。你知道吗

您需要使用双下划线:

def __init__(self, *args, **kw):

方法_init_对Python没有特殊意义,在实例化时不会被调用。你知道吗

相关问题 更多 >