Python设计——初始化、设置和获取类属性

标签 python class oop scientific-computing class-attributes

我有一个类,其中一个方法首先需要验证一个属性是否存在,否则调用一个函数来计算它。然后,确保该属性不是 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 block 可能有点矫枉过正,因为这个类并没有真正与其他类交互,它只需要数据和计算一堆东西。

最佳答案

首先,您可以使用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__ 中的属性,否则你将以无限递归结束

关于Python设计——初始化、设置和获取类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41522083/

相关文章:

python - conda 错误 : Downloaded bytes did not match Content-Length while trying to download cudnn using conda

javascript - 如何获取 django View 的 url 字符串?

python - 如何从 yaml 文件中删除文本 "!!omap"?

Java:在没有 KeyListener 或使用任何其他自定义类的情况下捕获按键事件

c++ - 对象组合促进代码重用。 (T/F,为什么)

python - 如何防止在 __init__() python 中创建对象

oop - VB6 是否允许仅通过命名其数据类型来引用 Form 实例作为单例?或者发生了什么?

python - 如何从键值对列表创建 Spark Row

objective-c - 无法从 Cocoa 中的不同类访问变量

c++ - 如何使用 nullptr 初始化同一类对象的静态指针数组?