【问题标题】:nesting of properties vs setters and getters in pythonpython中属性与setter和getter的嵌套
【发布时间】: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


【解决方案1】:

我相信你把问题复杂化了。如果你想阻止访问 OurAtt 的属性,@property 装饰器应该与OurAtt 一起使用。 OurAtt 类的实例将始终实现这种受保护的访问行为,包括当它们是 OurClass 的成员时。你不需要对OurClass 中的@property 装饰器做任何事情,除非你想阻止修改该类的成员。

我认为,这可以完成您想要完成的工作。它在 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.

【讨论】:

  • 感谢 Austin,class OurClass(): # 从对象继承被删除。 def __init__(self): self.OurAttr = OurAttr() oc = OurClass() oc.OurAttr.setLog() oc.OurAttr.clearLog() oc.OurAttr.log = False # 不引发异常,如果我删除对象会发生什么继承?
  • 我不知道,几分钟的搜索并没有启发我。您必须尝试一下,看看是否可以诊断出发生了什么。
  • 如果我们不从 Object 继承,它将是旧样式类并且不支持装饰器。这就是这种行为的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-18
  • 2018-11-08
相关资源
最近更新 更多