定义了一个类,运行有报错
本帖最后由 坚强的蚂蚁 于 2020-1-8 14:36 编辑>>> class D:
def __init__(self,size = 10):
self.size = size
def __getSize__(self):
return self.size
def __setSize__(self,value):
return self.value
def __delSize__(self):
del self.size
x = property(getSize,setSize,delSize)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 10, in D
NameError: name 'getSize' is not defined
新手小白求助:跟着小甲鱼的视频操作,定义了这样一个类,但是有报错,不知道哪里出了问题,求大神指导
自定义方法不用加下划线的。
class D:
def __init__(self,size = 10):
self.size = size
def getSize(self):
return self.size
def setSize(self,value):
return self.value
def delSize(self):
del self.size
x = property(getSize,setSize,delSize) zltzlt 发表于 2020-1-8 18:00
自定义方法不用加下划线的。
谢谢,没注意,确实是多加下划线了。代码里面定义setSize的时候修改了下,原先的有问题
class D:
def __init__(self,size = 10):
self.size = size
def getSize(self):
return self.size
def setSize(self,value):
self.size = value
def delSize(self):
del self.size
x = property(getSize,setSize,delSize) >>> class D:
def __init__(self,size = 10):
self.size = size
def getSize(self):
return self.size
def setSize(self,value):
self.size = value
def delSize(self):
del self.size
x = property(getSize,setSize,delSize)
SyntaxError: unexpected indent
>>> class D:
def __init__(self,size = 10):
self.size = size
def getSize(self):
return self.size
def setSize(self,value):
self.size = value
def delSize(self):
del self.size
x = property(getSize,setSize,delSize)
>>> d = D()
>>> d.x = 1
>>> d.x
1
>>> d.size
1
>>> del d.size
>>> d.x
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
d.x
File "<pyshell#2>", line 5, in getSize
return self.size
AttributeError: 'D' object has no attribute 'size'
>>> d.x = 11
>>> d.x
11
>>>
自己记录下操作过程,第一个红字报错,是我语法问题,没对齐。后面的报错是因为我把size属性删除了。size重新赋值,显示结果正常
页:
[1]