吸气剂副作用 [英] Getter with side effect

查看:174
本文介绍了吸气剂副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类,其对象用
初始化了一堆XML代码。该类有能力从XML中提取各种参数,并将其缓存在对象状态变量中。这些参数的潜在数量很大,最有可能的是,用户不需要其中的大部分。这就是为什么我决定执行懒惰的初始化。在下面的测试案例中,这样一个参数是 title 。当用户第一次尝试访问它时,getter函数解析XML,正确初始化状态变量并返回它的值:

  def __init __(self,xml = None):
self.xml = xml
self.title = None

def get_title(self):
如果self .__ title是None:
self .__ title = self .__ title_from_xml()
返回self .__ title
$ b def set_title(self,价值):
self .__ title = value

title = property(get_title,set_title,None,Citation title)

def __title_from_xml(self):
#parse XML并返回标题
返回标题

这看起来不错,对我来说工作得很好。不过,我对这个事实感到不安,因为吸气剂功能实际上是一个设置者,因为它对对象有非常显着的副作用。这是一个合理的关注吗?如果是这样,我应该如何解决它?

解决方案

虽然吸气剂肯定会产生副作用,考虑一个坏的副作用。由于getter总是返回相同的东西(禁止任何介入的状态变化),所以它没有用户可见的副作用。这是属性的典型用法,所以没有什么值得关注的。


I create a class whose objects are initialized with a bunch of XML code. The class has the ability to extract various parameters out of that XML and to cache them inside the object state variables. The potential amount of these parameters is large and most probably, the user will not need most of them. That is why I have decided to perform a "lazy" initialization.

In the following test case such a parameter is title. When the user tries to access it for the first time, the getter function parses the XML, properly initializes the state variable and return its value:

class MyClass(object):     
    def __init__(self, xml=None):
        self.xml  = xml
        self.title = None

    def get_title(self):
        if self.__title is None:
            self.__title = self.__title_from_xml()
        return self.__title

    def set_title(self, value):
        self.__title = value

    title = property(get_title, set_title, None, "Citation title")

    def __title_from_xml(self):
        #parse the XML and return the title
        return title         

This looks nice and works fine for me. However, I am disturbed a little bit by the fact that the getter function is actually a "setter" one in the sense that it has a very significant side effect on the object. Is this a legitimate concern? If so, how should I address it?

解决方案

While the getter certainly performs a side-effect, that's not traditionally what one would consider a bad side-effect. Since the getter always returns the same thing (barring any intervening changes in state), it has no user-visible side-effects. This is a typical use for properties, so there's nothing to be concerned about.

这篇关于吸气剂副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆