在python中嵌套属性vs setter和getter

时间:2016-01-27 06:09:20

标签: python properties getter-setter

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和属性的新手。提前致谢

1 个答案:

答案 0 :(得分:1)

我相信你的问题太复杂了。如果您想阻止访问OurAtt的属性,@property装饰器应该与OurAtt一起使用。 OurAtt类的实例将始终实现此受保护访问行为,包括它们是OurClass的成员时。除非您想要阻止修改该类的成员,否则您无需对@property中的OurClass装饰器执行任何操作。

我认为,这是你想要完成的事情。它的运行频率低于2.7 - 如果你使用的是早期版本,你的里程可能会有所不同。

class OurAttr(object):
    def __init__(self):
        self._log = False

    @property
    def log(self):
        return self._log

    @log.setter
    def log(self, value):
        raise AttributeError("Cannot set 'log' attribute directly.")

    @log.deleter
    def log(self):
        raise AttributeError("Cannot delete 'log' attribute directly.")

    def setLog(self):
        self._log = True
        print "Log is", self._log

    def clearLog(self):
        self._log = False
        print "Log is", self._log

class OurClass(object):
    def __init__(self):
        self.OurAttr = OurAttr()

oc = OurClass()
oc.OurAttr.setLog()
oc.OurAttr.clearLog()
oc.OurAttr.log = False   # Raises exception

输出是:

$ python2.7 test.py
Log is True
Log is False
Traceback (most recent call last):
  File "test.py", line 33, in <module>
    oc.OurAttr.log = False
  File "test.py", line 11, in log
    raise AttributeError("Cannot set 'log' attribute directly.")
AttributeError: Cannot set 'log' attribute directly.