开发者

what does this code snippet do?

开发者 https://www.devze.com 2022-12-17 13:45 出处:网络
can somebody give me an explanation about the following code? from twisted.internet import protocol, reactor

can somebody give me an explanation about the following code?

from twisted.internet import protocol, reactor
from twisted.protocols import basic

class FingerProtocol(basic.LineReceiver):
    def lineReceived(self, user):
        self.transport.write(self.factory.getUser(user)+"\r\n")
        self.transport.loseConnection()

class FingerFactory(protocol.ServerFactory):
    protocol = FingerPro开发者_JAVA技巧tocol

    def __init__(self, **kwargs):  # whats is ** ??
        self.users = kwargs

    def getUser(self, user):
        return self.users.get(user, "No such user")

reactor.listenTCP(1079, FingerFactory(moshez='Happy and well'))  
# explain call to fnger factory??


It's keyword argument notation.


The call to FingerFactory (a strange name, BTW) is instantiating a FingerFactory object. The parameters to that call are passed to the __init__ function of the class, where they are accepted by the **kwargs parameter as a dictionary:

{'moshez': 'Happy and well'}

So this is assigned to the users attribute of the new FingerFactory instance.


And the other question, regarding FingerFactory call.

That's how you do instantiation in Python. You don't use a new keyword. You just call the class as though it were a function. The constructor of the class is __init__

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号