Discuss / Python / 为什么不加下划线就一直出错呢

为什么不加下划线就一直出错呢

Topic source

狗不理翔

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

class Screen(object):

@property
def width(self):
    return self.width
@width.setter
def width(self,value):
    self.width=value

@property
def height(self):
    return self.height
@height.setter
def height(self,value):
    self.height=value

@property
def resolution(self):
    return self.width*self.height

求大神帮忙仔细解释下为什么要加这个下划线?不加为什么一直出错呢?原因是什么?

廖雪峰

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

因为self.width实际上是调方法,而不是变量。

不是需要下划线,而是需要不同的变量名区分:

@property
def width(self):
    return self.value_of_width

@width.setter
def width(self,value):
    self.value_of_width = value

狗不理翔

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

谢廖老师。

class Screen(object):

    @property
    def width_operation(self):
        return self.width
    @width_operation.setter
    def width_operation(self,value):
        self.width=value

就是说上面这样其实是可以的,只要方法名和属性名不是一样的。如果不加下划线,恰好方法名和属性名又是一样的话,那么调用的就是方法,会出现一直重复调用的情况是吧。 另外,廖老师网站能不能设计成别人回复我的评论在个人账户的地方显示出来有未读消息呢(就像新浪微博那样),菜鸟只是提一个建议,也不知道这样的实现是不是很困难,只是觉得别人如果回复了我的评论,但是我又不记得在哪里评论的,还得一页一页去翻挺麻烦的~~

Eliefly

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

但下划线_什么作用,后面两种方式都可以。

class Screen(object):
    @property
    def width(self):
        return self._width
    @width.setter
    def width(self,value):
        self._width=value
    @property
    def height(self):
        return self._height
    @height.setter
    def height(self,value):
        self._height=value
    @property
    def resolution(self):
        return self._width * self._height    

# >>> s=Screen()
# >>> s.width=1024
# >>> s.height=768
# >>> s.resolution
# 786432

# >>> s=Screen()
# >>> s._width=1024
# >>> s._height=768
# >>> s.resolution
# 786432

   __author__ = 'Jay'
class Screen(object):
    @property
    def width(self):
        return self.w
    @width.setter
    def width(self,value):
        self.w=value
    @property
    def height(self):
        return self.h
    @height.setter
    def height(self,value):
        self.h=value

    @property
    def resolution(self):
        return self.w*self.h

s=Screen()
s.width=1024            #实例化对象调用的是函数width
s.height=768            #实例化对象调用的是函数height
print(s.resolution)
s.w=1024                #实例化对象调用的是变量w
s.h=768                    #实例化变量调用的是变量h
print(s.resolution)

如上解释应该可以明白了吧。廖老师加下划线只是为了区分变量和函数。


  • 1

Reply