【发布时间】:2016-05-03 23:16:07
【问题描述】:
class OurAtt():
def __init__(self):
self.Log = False
def setLog(self):
self.Log = True
def clearLog(self):
self.Log = False
class OurClass(object):
def __init__(self):
self.__OurAtt = OurAtt()
@property
def OurAtt(self):
return self.__OurAtt
@OurAtt.setter
def OurAtt(self, val):
raise Exception("can't modify the attribute" )
x = OurClass()
x.OurAtt.setLog()
print x.OurAtt.Log # print True
x.OurAtt.Log = False
print x.OurAtt.Log # sets to False Aim set this through function call x.OurAtt.setLog() I want to restrict the access, something like private variable.
最终目标是 Log 应该是 OurAttr 的属性,并且应该受到 getter 和 setter 或属性的保护。它就像属性的嵌套。和层次结构应该像 object.OurAttr.Log 一样维护
我研究并得到了以下链接。
Python: multiple properties, one setter/getter
但它没有达到我的目标。
我实际上是 getter、setter 和属性的新手。在此先感谢
【问题讨论】:
-
那么你的代码到底有什么问题呢?此外,您似乎正在使用 python 2,因此您的类必须是新样式类才能正常工作。你的类应该继承自
object。 -
感谢鲁尼,刚刚添加了更改。有什么办法可以解决这个问题?
-
我不清楚你的问题。您当前拥有的代码(已被编辑器更改)以何种方式无法按预期工作?
-
编辑了帖子。目的是通过函数调用 x.OurAtt.setLog() 设置 self.Log 我想限制访问,类似于私有变量。
-
您为什么认为这样做可以帮助您实现目标?
标签: python properties getter-setter