How to get value of parent class
Jean-Pierre Bergamin
james at ractive.ch
Mon Apr 12 16:40:37 EDT 2004
Joe Mason wrote:
>> 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".
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
More information about the Python-list
mailing list