类实例覆盖属性

时间:2014-11-28 13:17:31

标签: python class

我已经用Python编写了一个用于计算的类,它看起来像:

default = {…}

class Case(object):
    def __init__(self, name, wt, wd, ft, bc, burnup, cr_state):
        self.name = name
        self.burnup = burnup
        self.infn = 'fa-'+faType+'-'+str(self.burnup)+'-'+self.name
        self.data = default
        self.data['caseName'] = name
        self.data['water-temp'] = str(wt)
        self.data['water-den'] = str(wd)
        self.data['fuel-temp'] = str(ft)
        self.data['boron-con'] = str(bc)
        self.cr_state = cr_state
        self.data['cr_state'] = cr_state
        self.data['burnup'] = str(burnup)

实际上它实现了更多的方法,但这仅仅是为了说明。

问题在于,当我尝试创建此类的不同实例时,他们会得到相同的属性,例如:

basis = Case('basis', 578.0, 0.71614, 578.0, 0.00105, 0, 'empty')
wt450 = Case('wt450', 450.0, 0.71614, 578.0, 0.00105, 0, 'empty')

之后如果我检查:

print basis.data == wt450.data

它返回True。问题的根源在哪里?

1 个答案:

答案 0 :(得分:0)

与jonrsharpe州的评论一样,您可以使用`dict.copy方法复制default字典的内容。

class Case(object):
    def __init__(self, name, wt, wd, ft, bc, burnup, cr_state):
        self.name = name
        self.burnup = burnup
        self.infn = 'fa-'+faType+'-'+str(self.burnup)+'-'+self.name
        # Copy the content of the dict
        self.data = default.copy()
        # Overwrite data's default values
        self.data['caseName'] = name
        self.data['water-temp'] = str(wt)
        self.data['water-den'] = str(wd)
        self.data['fuel-temp'] = str(ft)
        self.data['boron-con'] = str(bc)
        self.cr_state = cr_state
        self.data['cr_state'] = cr_state
        self.data['burnup'] = str(burnup)

或者,如果您希望将值与默认值保持同步,则可以创建一个方法,该方法将从实例中获取值,如果找不到该值,则使用默认dict中的值。它看起来像这样:

class Case(object):
    def __init__(self, name, wt, wd, ft, bc, burnup, cr_state):
        self.name = name
        self.burnup = burnup
        self.infn = 'fa-'+faType+'-'+str(self.burnup)+'-'+self.name
        # We create a NEW dictionary to hold the overwritten values
        self.data = {}
        # Write data to OUR OWN dict
        self.data['caseName'] = name
        self.data['water-temp'] = str(wt)
        self.data['water-den'] = str(wd)
        self.data['fuel-temp'] = str(ft)
        self.data['boron-con'] = str(bc)
        self.cr_state = cr_state
        self.data['cr_state'] = cr_state
        self.data['burnup'] = str(burnup)
    def property(name):
        """
        Return the value of `name`, if name wasn't defined, then use the
        value from default.
        """
        # Return the property from our own dict. If it can't find the property
        # then get it from the default dict. If the property doesn't exists
        # returns None.
        return self.data.get(name, default.get(name))

# Then
print basis.property('caseName') == wt450.property('caseName')
> False