How to get value of parent class

  • Thread starter Jean-Pierre Bergamin
  • Start date
J

Jean-Pierre Bergamin

Hello

I have the following class structure:


class MyServer:

x= 0

class MyHandler(SocketServer.StreamRequestHandler):
def handle(self):
if x: # <---- How to get the X from the parent class?
# Or how to pass a value to this class anyway?
do_something()
else:
do_something_else()

def start_server(self):
s = SocketServer.TCPServer(('', 1234), self.MyHandler)
s.server_forevert()

server = MyServer
server.x = 10
server.start_server()



How is it possible to get the value of x from the class MyServer within the
MyHandler class?
The object of self.MyHandler is instantiated everytine the
SocketServer.TCPServer calls handle, so it's not possible to create an
instance of MyHandler an pass it the value.

Or ist there any other possibility to pass the class MyHandler some values?


Thanks in advance.


James
 
J

Joe Mason

Hello

I have the following class structure:


class MyServer:

x= 0

class MyHandler(SocketServer.StreamRequestHandler):
def handle(self):
if x: # <---- How to get the X from the parent class?
# Or how to pass a value to this class anyway?
do_something()

Just say "MyServer.x".

Joe
 
J

Jean-Pierre Bergamin

Joe said:
Just say "MyServer.x".

Hmmm. The TCPServer class instanciates a new
SocketServer.StreamRequestHandler object everytime it uses it. Therefore
it's not in the context of the MyServer class. That's why it didn't work.

It's like in this example:

class A:
x = 0

class B:
def get_x(self):
print A.x


a = A()
a.x = 10
b = a.B()
b.get_x() # prints out 0 (not 10 as someone might expect)


As a workaroud it did it this way:

def start_server(self):
handler = self.MyHandler
handler.x = self.x
s = SocketServer.TCPServer(('', 1234), handler)
s.server_forever()


But thanks for the hint.


James
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,184
Messages
2,570,978
Members
47,561
Latest member
gjsign

Latest Threads

Top