Addarsh Chandrasekar
Addarsh Chandrasekar

Reputation: 578

Understanding syntax in Python

I am trying to use PodSixNet library in Python to implement a multiplayer game. As I have seen a few tutorials online, the server file is as follows:

import PodSixNet.Channel
import PodSixNet.Server
from time import sleep

class ClientChannel(PodSixNet.Channel.Channel):
    def Network(self, data):
        print data

class BoxesServer(PodSixNet.Server.Server):
    channelClass = ClientChannel

    def __init__(self, *args, **kwargs):
         PodSixNet.Server.Server.__init__(self, *args, **kwargs)

What does the line channelClass = ClientChannelmean?

channelClass is definitely not an instance of the ClientChannel class because the instance declaration is not correct. So what is it then?

Upvotes: 0

Views: 96

Answers (3)

skyking
skyking

Reputation: 14390

In python classes are first class objects. You can assign them to a variable just like any other object. The channelClass = ClientChannel means to assign to BoxesServer.channelClass the class ClientChannel (as a class variable), later BoxesServer.channelClass can be used just like ClientChannel.

This could be useful if you derive from BoxesServer and then assign in the derived class another class for channelClass which would mean that you can customize which class to be used in place of ClientChannel. You can for example in a method write:

def getChannelInstance(self, *args, **kwds):
     return self.channelClass(*args, **kwds)

...and it will return an instance as appropriate depending on the class.

Upvotes: 0

DevLounge
DevLounge

Reputation: 8437

This is meant for deferred use.

Later on, any instantiation of channelClass will result in ClientChannel instances.

See this as a way to allow the developer to use whatever class he wants, but the PodSixNet.Server.Server subclasses will always instantiate channelClass as they cannot know what real class will be given by the developer.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121306

All this does is create the BoxesServer.channelClass class attribute. It is just a reference to another class.

Why would you do that? Well, the PodSixNet.Server.Server is flexible, it doesn't hardcode the class it'll use to create channels for new connections. Instead, it'll look for the self.channelClass attribute, and use that to create new channel instances. See the Server.handle_accept() method source:

self.channels.append(self.channelClass(conn, addr, self, self._map))

Calling self.channelClass() then creates an instance of whatever class is assigned to that attribute. This lets you swap out the channel class easily when defining new subclasses.

Note that the PodSixNet.Server.Server() class can also take the channel class as an argument when creating an instance. That'll then override the class attribute you set.

Upvotes: 4

Related Questions