Python问题采样

代码执行顺序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Screen(object):
_width = 20
print('1',_width)

def __init__(self):
print('2',self._width)
self._width = 100
print('3',self._width)

@property
def width(self):
print('6',self._width)
return self._width


_width = 30
print('4',_width)

if __name__ == '__main__':
s = Screen()
print('5',s.width)

输出结果:

1
2
3
4
5
6
1 20
4 30
2 30
3 100
6 100
5 100

问题:

  1. __init__是最后执行的?
  2. 1处的_width是否为属性?因为6是在1后执行的。
  3. 如果1处的不是属性的话,如果在2处不写self._width,写_width错误原因是什么?

问题1解答:

修改代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Screen(object):
_width = 20
_height = 20
print('1',_width)

def __init__(self):
print('2',self._width)
self._width = 100
print('3',self._width)

@property
def width(self):
print('6',self._width)
return self._width


_width = 30
print('4',_width)

控制台:

1
2
3
4
5
6
7
8
1 20
4 30
>>> s = Screen()
2 30
3 100
>>> s.width
6 100
100

class MyObject(object):

  是先执行MyObject?还是等到用的时候执行MyObject呢?

  答案是初始化MyObject, 但不执行init方法, 也就是说等到用到的时候再执行初始化操作。

​ 所以看到打印出了1,4,没看到2 和 3.

2,3解答:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Screen(object):
_width = 20
_height = 20
print('1',_width)

def __init__(self):
print('2',self._width)
self._width = 100
print('3',self._width)

@property
def width(self):
print('6',self._width)
return self._width


_width = 30
print('4',_width)

if __name__ == '__main__':
s = Screen()
print('5',s.width)

输出:

1
2
3
4
5
6
7
8
9
10
11
1 20
4 30
2 30
3 100
6 100
5 100
>>> dir(s)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_height', '_width', 'width']
>>> s.height = 200
>>> s.height
200

所以说在1处使用的_width_height已经成为属性了,所以解释了3处为什么需要使用self._width