为了澄清Paul's answer,这里有一个简单的例子:
class Test(object):
print "Class being defined"
def __init__(self):
print "Instance being created"
for _ in range(3):
t = Test()
由此产生的输出将是:
Class being defined
Instance being created
Instance being created
Instance being created
在class 定义内但在方法definition 之外的代码在定义类时只运行一次。
如果您希望代码在创建实例时运行,它应该在__init__ 实例方法中(或者,偶尔在__new__ 类方法)。但是,请注意,如果您为子类定义__init__,您可能应该确保它也调用超类的__init__:
class AError(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs) # call the superclass
print 'error occur' # print your message
这确保子类支持超类的参数;对于Exception,您可以例如传递错误信息:
>>> raise AError("Something went wrong.")
error occur # your message gets printed when the instance is created
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
raise AError("Something went wrong.")
AError: Something went wrong. # the error message passes through to the traceback
有关*args, **kwargs 语法的解释,如果您不熟悉它,请参阅例如What does ** (double star) and * (star) do for parameters?。您也可以使用super 来调用超类方法,参见例如Understanding Python super() with __init__() methods.