Dav*_*vid 2 python oop python-3.x
考虑以下代码
class Foo:
i = 1 # initialization
def __init__(self):
self.i += 1
t = Foo()
print(t.i)
Run Code Online (Sandbox Code Playgroud)
i的初始化究竟何时发生?在init方法执行之前还是之后?
前。
该__init__方法Foo在实例化之前不会运行。i=1每当在代码中遇到类定义时运行
您可以通过添加打印语句来查看这一点:
print('Before Foo')
class Foo:
i = 1
print(f'Foo.i is now {i}')
def __init__(self):
print('Inside __init__')
self.i += 1
print(f'i is now {self.i}')
print('After Foo')
print('Before __init__')
foo = Foo()
print('After __init__')
Run Code Online (Sandbox Code Playgroud)
打印:
Before Foo
Foo.i is now 1
After Foo
Before __init__
Inside __init__
i is now 2
After __init__
Run Code Online (Sandbox Code Playgroud)
但是请注意,您self.i += 1 不会修改 class 属性Foo.i。
foo.i # This is 2
Foo.i # This is 1
Run Code Online (Sandbox Code Playgroud)