Discuss / Python / 为啥要写成_width呀?就是为啥加个下划线

为啥要写成_width呀?就是为啥加个下划线

Topic source

作业是做出来了,但是不太明白为什么有个下划线。

_width

取消下划线的话,报错

 [Previous line repeated 996 more times]

RecursionError: maximum recursion depth exceeded

提示超过最大递归深度,这是为啥呀?

s丢pid

#3 Created at ... [Delete] [Delete and Lock User]

我的理解:

1、self._width只是一个名称,我试了下你也可以换成其他名字,比如self.test之类的;self._width这样命名的目的,按照之前的讲解,就是你理论上可以访问我但是请将我认定为一个私有变量。

2、你直接去掉下划线当然不行,在width()中return返回width()方法本身,岂不是陷入无限递归?

3、@property中的self._width其实调用的是@width.setter中给出的self._width,即先通过setter将外部给定参数value读入到self._width,再通过@property赋给self.width。

将_width换成其他形式(除width外),都是可以的,例如我把_width换成width1,把_height换成height2,如下:执行结果也是成功的!

class Screen(object):

    @property

    def width(self):

        return self.width1

    @width.setter

    def width(self, value):

        self.width1 = value

    @property

    def height(self):

        return self.height2

    @height.setter

    def height(self, value):

        self.height2= value

    @property

    def resolution(self):

        return self.height2*self.width1

# 测试:

s = Screen()

s.width = 1024

s.height = 768

print('resolution =', s.resolution)

if s.resolution == 786432:

    print('测试通过!')

else:

    print('测试失败!')


  • 1

Reply