Python(Jython) - 我可以在属性setter和getter函数中访问变量名吗?

时间:2017-09-03 17:50:42

标签: python jython python-2.5 jython-2.5

我有以下课程。 self.valueself.name的行为完全相同。只有变量名称不同。我怎样才能重写这个,这样我就不必定义两个基本相同的属性定义,因为我正在使用不同的变量名?我可以访问setter和getter函数中的变量名,也可以使用getattr()setattr()

我正在使用:Jython 2.5.2

class StateMachineState(object):
def __init__(self, value, name):
    self.valueHash = None
    self.nameHash = None
    self.stateHash = None
    self.value = value
    self.name = name

def __eq__(self, other):
    return self.stateHash == other.stateHash if self.__class__ == other.__class__ else False

def __str__(self):
    return "value = %s (%s) - name = %s (%s) - (%s)" % (self.value, self.valueHash, self.name, self.nameHash, self.stateHash)

def getValue(self):
    return self._value

def setValue(self, value):
    try:
        str(value)
        hash(value)
        self.valueHash = hash(str(value) + str(value.__class__))
        self._value = value
    except:
        self.valueHash = None
        self._value = None
    self.stateHash = hash(str(self.valueHash) + str(self.nameHash))

def getName(self):
    return self._name

def setName(self, name):
    try:
        str(name)
        hash(name)
        self.nameHash = hash(str(name) + str(name.__class__))
        self._name = name
    except:
        self.nameHash = None
        self._name = None
    self.stateHash = hash(str(self.valueHash) + str(self.nameHash))

value = property(getValue, setValue)
name = property(getName, setName)

1 个答案:

答案 0 :(得分:0)

我能够使用包装函数来解决这个问题:

class StateMachineState(object):
    def __init__(self, value, name):
        self.valueHash = None
        self.nameHash = None
        self.stateHash = None
        self.value = value
        self.name = name

    def __eq__(self, other):
        return self.stateHash == other.stateHash if self.__class__ == other.__class__ else False

    def __str__(self):
        return "( %s (%s) , '%s' (%s) ) - (%s)" % (self.value, self.valueHash, self.name, self.nameHash, self.stateHash)

    def getAttrValue(self, attrName):
        return getattr(self, '_' + attrName)

    def setAttrValue(self, attrName, value):
        valueName = '_%s' % attrName
        hashName = '%sHash' % attrName
        try:
            str(value)
            hash(value)
            setattr(self, hashName, hash(str(value) + str(value.__class__)))
            setattr(self, valueName, value)
        except:
            setattr(self, hashName, None)
            setattr(self, valueName, None)
        self.stateHash = hash((self.valueHash, self.nameHash))

    def getValue(self):
        return self.getAttrValue('value')

    def setValue(self, value):
        self.setAttrValue('value', value)

    def getName(self):
        return self.getAttrValue('name')

    def setName(self, name):
        self.setAttrValue('name', name)

value = property(getValue, setValue)
name = property(getName, setName)