Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中使用属性装饰器期间在init中赋值_Python_Decorator - Fatal编程技术网

在python中使用属性装饰器期间在init中赋值

在python中使用属性装饰器期间在init中赋值,python,decorator,Python,Decorator,我试图学习python中的@property。我刚刚写了一个例子: class sample(object): def __init__(self,a): self.x=a ---> why is this assignment mandatory here?, I tried without and fail @property def x(self): print "getter" return self.__

我试图学习python中的@property。我刚刚写了一个例子:

class sample(object):
    def __init__(self,a):
        self.x=a   ---> why is this assignment mandatory here?, I tried without and fail
    @property
    def x(self):
        print "getter"
        return self.__x
    @x.setter
    def x(self,a):
        print "setter"
        if a<=100 and a>=0:
           self.__x=a
        elif a<0:
           self.__x=0
        else:
           self.__x=100


ob=sample(30)
print ob.x
类示例(对象):
定义初始化(self,a):
self.x=a--->为什么这个任务在这里是强制性的?我尝试了,但没有成功
@财产
def x(自我):
打印“getter”
返回自我
@x、 塞特
def x(自身,a):
打印“setter”
如果a=0:
自我。uux=a

如果a公共
x
是一个函数(实际上是两个)。它覆盖实际的变量赋值。所以,如果你有属性,当你有属性的时候

obj.x = 5
它相当于调用值为5的
@x.setter
函数。类似地,当您使用
obj.x
时,它会调用
obj.x()
属性。 实际变量是“private”
self.\ux

因此,一般来说,第一个任务不是“需要的”。但是,在这种特殊情况下,当您调用
print(obj.x)
时,相应的属性会尝试查找尚未存在的
obj.\uuux
。但是,如果您在第一行中赋值
self.x=30
,它将调用带有参数30的
@x.setter
函数。此函数创建
self.\uux
变量,因此它现在存在,并且当您
print(obj.x)


注意:顺便说一下,对于私有变量,更喜欢
\ux
(单下划线)。双下划线具有特殊含义

公共
x
是一个函数(实际上是两个)。它覆盖实际的变量赋值。所以,如果你有属性,当你有属性的时候

obj.x = 5
它相当于调用值为5的
@x.setter
函数。类似地,当您使用
obj.x
时,它会调用
obj.x()
属性。 实际变量是“private”
self.\ux

因此,一般来说,第一个任务不是“需要的”。但是,在这种特殊情况下,当您调用
print(obj.x)
时,相应的属性会尝试查找尚未存在的
obj.\uuux
。但是,如果您在第一行中赋值
self.x=30
,它将调用带有参数30的
@x.setter
函数。此函数创建
self.\uux
变量,因此它现在存在,并且当您
print(obj.x)


注意:顺便说一下,对于私有变量,更喜欢
\ux
(单下划线)。双下划线有特殊的含义

当您检索
x的值时,如果不先设置它,您会期望发生什么?回溯(最近一次调用):文件“/Users/syam.mohan/PycharmProjects/untitled2/TEST/qqq.py”,第31行,在打印ob.x文件“/Users/syam.mohan/PycharmProjects/untitled2/TEST/qq.py”,第15行,在x中返回self.\uuux AttributeError:'sample'对象没有属性'\usample\uuux'是。为什么这会让你感到惊讶?当你检索
x
的值而不首先设置它时,你会期望发生什么?回溯(最后一次调用):文件“/Users/syam.mohan/PycharmProjects/untitled2/TEST/qqq.py”,打印ob.x文件“/Users/syam.mohan/PycharmProjects/untitled2/TEST/qq.py”第31行,第15行,在x中返回self.\uuux AttributeError:'sample'对象没有属性'\usample\uuux'是。为什么你会感到惊讶?