ben-ju1
ben-ju1

Reputation: 11

Python how to add a new property on a subclass

I created a class Server implementing socketserver.BaseRequestHandler.

I'm looking to add a self.buffer = '' attribute.

Here is the code I came up with :

class Server(socketserver.BaseRequestHandler):

  def __init__(self, request, client_address, server):
    super(Server, self).__init__(request=request, client_address=client_address, server=server)
    self.buffer = ''

  def get_first_buffer(self):
    self.buffer = 'Successfully connected.'

  def handle(self):
    if self.buffer == '':
        self.get_first_buffer()
        print(self.buffer)

Here is the error I got

Exception happened during processing of request from ('127.0.0.1', 33564)
AttributeError: 'Server' object has no attribute 'buffer'

Upvotes: 1

Views: 95

Answers (1)

Aplet123
Aplet123

Reputation: 35512

When initializing BaseRequestHandler, it actually calls handle, which means that self.buffer must be set before then in order for the if self.buffer == '' check to work:

def __init__(self, request, client_address, server):
  # move this before the super init
  self.buffer = ''
  super(Server, self).__init__(request=request, client_address=client_address, server=server)

Upvotes: 2

Related Questions