3

我有一个类,其中一个方法首先需要验证一个属性是否存在,否则调用一个函数来计算它。然后,确保该属性不是None,它对它执行一些操作。我可以看到两种略有不同的设计选择:

class myclass():
    def __init__(self):
        self.attr = None

    def compute_attribute(self):
        self.attr = 1

    def print_attribute(self):
        if self.attr is None:
            self.compute_attribute()
        print self.attr

class myclass2():
    def __init__(self):
        pass

    def compute_attribute(self):
        self.attr = 1
        return self.attr

    def print_attribute(self):
        try:
            attr = self.attr
        except AttributeError:
            attr = self.compute_attribute()
        if attr is not None:
            print attr

在第一个设计中,我需要确保None预先设置好所有的类属性,这样可以变得冗长但也可以明确对象的结构。

第二种选择似乎是使用更广泛的一种。但是,出于我的目的(与信息论相关的科学计算)try except,考虑到这个类并没有真正与其他类交互,它只需要数据并计算一堆东西,因此在任何地方使用块可能有点过头了。

4

2 回答 2

0

首先,您可以使用hasattr检查对象是否具有属性,True如果属性存在则返回。

hasattr(object, attribute) # will return True if the object has the attribute

其次,您可以在 Python 中自定义属性访问,您可以在此处阅读更多信息:https ://docs.python.org/2/reference/datamodel.html#customizing-attribute-access

基本上,您覆盖了__getattr__实现此目的的方法,因此类似于:

类 myclass2(): def init (self): 通过

def compute_attr(self):
    self.attr = 1
    return self.attr

def print_attribute(self):
    print self.attr

def __getattr__(self, name):
    if hasattr(self, name) and getattr(self, name)!=None:
        return getattr(self, name):
    else:
        compute_method="compute_"+name; 
        if hasattr(self, compute_method):
            return getattr(self, compute_method)()

确保您仅用于getattr访问其中的属性,__getattr__否则您将得到无限递归

于 2017-01-07T14:16:22.377 回答
-1

根据jonrsharpe linked 的答案,我提供了第三种设计选择。MyClass这里的想法是,客户端或自身内部的代码根本不需要特殊的条件逻辑MyClass。相反,装饰器应用于对属性进行(假设昂贵)计算的函数,然后存储该结果。

这意味着昂贵的计算是惰性完成的(仅当客户端尝试访问该属性时)并且只执行一次。

def lazyprop(fn):
    attr_name = '_lazy_' + fn.__name__

    @property
    def _lazyprop(self):
        if not hasattr(self, attr_name):
            setattr(self, attr_name, fn(self))
        return getattr(self, attr_name)

    return _lazyprop


class MyClass(object):
    @lazyprop
    def attr(self):
        print('Generating attr')
        return 1

    def __repr__(self):
        return str(self.attr)


if __name__ == '__main__':
    o = MyClass()
    print(o.__dict__, end='\n\n')
    print(o, end='\n\n')
    print(o.__dict__, end='\n\n')
    print(o)

输出

{}

Generating attr
1

{'_lazy_attr': 1}

1

编辑

Cyclone 的答案应用于 OP 的上下文:

class lazy_property(object):
    '''
    meant to be used for lazy evaluation of an object attribute.
    property should represent non-mutable data, as it replaces itself.
    '''

    def __init__(self, fget):
        self.fget = fget
        self.func_name = fget.__name__

    def __get__(self, obj, cls):
        if obj is None:
            return None
        value = self.fget(obj)
        setattr(obj, self.func_name, value)
        return value


class MyClass(object):
    @lazy_property
    def attr(self):
        print('Generating attr')
        return 1

    def __repr__(self):
        return str(self.attr)


if __name__ == '__main__':
    o = MyClass()
    print(o.__dict__, end='\n\n')
    print(o, end='\n\n')
    print(o.__dict__, end='\n\n')
    print(o)

输出与上面相同。

于 2017-01-07T14:11:43.943 回答