Zhe Li
Zhe Li

Reputation: 1153

Missing methods in Python class inheritance?

I am not very experienced with class inheritance. Please help me and have a look at the code below:

class Handle(STAFHandle):

    def __init__(self, HandleName):
        handle = STAFHandle.__init__(self, HandleName)
        self.initLogger(handle)

    def initLogger(self, handle):
        self.logger = Logging(handle, 'Test')

handle = Handle('test')
handle.logger.info('test')

it says submit method is not defined:

result = handle.submit(system, service, logRequest) 
AttributeError: 'NoneType' object has no attribute 'submit'

but if I change it to:

class Handle(STAFHandle):
    def __init__(self, HandleName):
        handle = STAFHandle.__init__(self, HandleName)

    def initLogger(self, handle):
        self.logger = Logging(handle, 'Test')

handle = Handle('test')
handle.initLogger(handle)
handle.logger.info('test')

it works. Why there is a difference? Thanks a lot!!

Cheers, Zhe

Upvotes: 1

Views: 699

Answers (1)

Katriel
Katriel

Reputation: 123772

STAFHandle.__init__ returns None. You probably want:

class Handle(STAFHandle):
    def __init__(self, handle_name):
        super(Handle, self).__init__(handle_name)
        self.initLogger()

    def initLogger(self):
        self.logger = Logging(self, 'Test')

handle = Handle('test')

Remember that __init__ methods take as their first argument an object, and modify that object. So when you call super(Handle, self).__init__(handleName) you are changing the properties of self instead of returning a new object. The difference between your two examples is that the variable handle in the two calls to initLogger refers to different things.

Notice that I have replaced the explicit STAFHandle.__init__ call with a super proxy; this is equivalent in this case but allows for more flexibility, since you can now change the inheritance of the class without breaking its __init__.

I've also changed HandleName to handle_name to conform with Python conventions (CamelCase refers to classes).

Upvotes: 4

Related Questions