如何在Python中覆盖属性getter

时间:2015-06-04 10:42:31

标签: python inheritance properties

我有一个名为sessionID的类。从那个类我已经派生了一个新类,并希望在属性getter和property setter中实现一些其他功能。我似乎有属性setter正常工作,但由于一些奇怪的原因,getter总是在基类上执行getter。你们中的任何人都知道我做错了什么,或者我可以改变什么“

基类:

class workflowerAPIBase(object):
    _sessionID = None
    _IP        = None

    @property
    def sessionID(self):
        return self._sessionID

    @sessionID.setter
    def sessionID(self, value):
        self._sessionID = value

后裔类:

class workflowerAPI(workflowerAPIBase):
    session = None

    @property
    def sessionID(self):
        # Try to get the previous sessionID from the Session ... 
        # we will still have to check if that sessionID is valid though
        if ( 'sessionID' in self.session ):
            self._sessionID = self.session['sessionID']

        # If no sessionID was found, try to use a default one for now
        # by generating a loginPrintersCloud using default login info
        if ( self._sessionID == None ) or ( self._sessionID == '' ):
            result = self.defaultlogin
            self._sessionID = result['sessionID']

        return self._sessionID

    @workflowerAPIBase.sessionID.setter
    def sessionID(self, value):
        # Store the new sessionID in our session for later use
        if ( self.session != None ):
            self.session['sessionID'] = value

        # call the inherited sessionID setter
        workflowerAPIBase.sessionID.fset( self, value )
        #super(workflowerAPI, self).sessionID(self, value)
#        self._sessionID = value

    def __init__(self, request):
        if request != None and request.session != None and request.session.has_key('sessionID'):
            self.session   = request.session
            self.sessionID = request.session['sessionID']

        super(workflowerAPI, self).__init__()

我不确定我做错了什么,但每次读取sessionID属性的值时,似乎都在workflowerAPIBase上调用getter,尽管我正在创建一个worflowerAPI的实例。

1 个答案:

答案 0 :(得分:-1)

在Python中,您不会覆盖方法,只需在派生类中隐藏原始方法。另一方面,装饰器只是用于函数调用的语法糖。所以

@workflowerAPIBase.sessionID.setter
def sessionID(self, value):
    ...

的缩写
def set_sessionID(self, value):
    ...
sessionID = workflowerAPIBase.sessionID.setter(set_sessionID)

使用基类中的getter和派生类中的setter设置sessionID。正确的是:

@sessionID.setter
def sessionID(self, value):
    ...