Python: How to invoke a method from outside a class?

Ste

I have a really short and easy question:

How to invoke the send() method from another python file/class? I want to send a message from another component to client (connection is established).

I thought Ijust have to get the reference of the singleton instance and then just "send" like this:

server = Server(ip,port)
server.send("hello")

If I do it like that, I get the error:

NoneType' object has no attribute 'send'

Maybe "self" is here the problem...

here is the server class:

class Server(threading.Thread):

    ##############################################################################
    # Server: Singleton Instance
    ##############################################################################
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Server, cls).__new__(cls, *args, **kwargs)
        return cls._instance    

    ##############################################################################
    # Constructor of Server
    ##############################################################################
    def __init__(self, host, port):
        threading.Thread.__init__(self)
        print "[SERVER____] Creating Server Thread"
        self.host = host
        self.port = port
        self.__reset__()  

    ##############################################################################
    # Resetting local attributes
    ##############################################################################
    def __reset__(self):   
        print "[SERVER____] Reset"         
        self.serverSock = None
        self.clientSock = None
        self.clientAddr = None
        self.clientData = None
        self.isRunning = None
        self.isWaiting = None

    ###########################################################################                
    def send(self, message):
        print "[SERVER____] Sending Message", message
        self.clientSock.send(message)

    ##############################################################################
    # Stop the Server: Close the Socket and Reset
    ##############################################################################
    def stop(self):            
        # Close The Client Socket
        if(self.clientSock): 
            self.clientSock.close()
            print "[SERVER____] Aborting Client Socket"
        # Close The Server Socket    
        if(self.serverSock): 
            self.serverSock.close()
            print "[SERVER____] Aborting Server Socket"
        # Reset the Member Fields
        self.__reset__()
        print "[SERVER____] Aborting Server Thread"
        self._Thread__stop()

    ##############################################################################
    # Server.start()
    ##############################################################################
    def run(self):          
        try:
            # Create The Socket
            self.serverSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            print "[SERVER____] Creating Server Socket"
            # Set Socket Options
            #self.serverSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1);
            # Bind The New Socket
            self.serverSock.bind((self.host, self.port))
            print "[SERVER____] Binding Server Socket"
            print "[SERVER____] IP: ", self.host, " Port: ", self.port
            # Set The Awaiting Flag
            self.isWaiting = True;
            # Start The Server Loop
            while self.isWaiting:
                # Listen On New Socket
                self.serverSock.listen(1)
                print "[SERVER____] Listening Server Socket"
                # Accept New Connection            
                self.clientSock, self.clientAddr = self.serverSock.accept()     
                print "[SERVER____] Accepting New Connection: " , self.clientAddr
                # Set The Running Flag
                self.isRunning = True;     
                # Serve The Connection
                while self.isRunning:
                    print "[SERVER____] Want to recv message...."
                    try:
                        # Receive A New Data Block    
                        self.clientData = self.clientSock.recv(config.BUFFERSIZE)
                        # Process The New Data Block
                        if not self.clientData:                       
                            print "[SERVER____] Reset By Client Connection"
                            break
                        else:    
                            print "[SERVER____] Receiving Message: ", self.clientData
                            parser = MessageParser()
                            parser.parseSMMessage(self.clientData)                    
                    except socket.error:
                        print "[SERVER_ERR] Error at receiving data from client."                            
        except Exception as exc:
            print "[SERVER____] Server Thread Exception ", exc
interjay

Your implementation of the singleton pattern is wrong, and this causes self.clientSock to be set to None before calling self.clientSock.send. The implementation is wrong because it will call __init__ each time you get the singleton instance. Basically, what happens is:

  1. You call Server(...) to get the instance.
  2. run is called on that instance. This sets self.clientSock.
  3. You call Server(...) to get the instance again. This will return the same instance due to your implementation of __new__, but __init__ will be called on it again and self.clientSock will be reset to None.
  4. Now the call to self.clientSock.send causes an exception.

I recommend avoiding using __new__ to implement a singleton if you need one (though not using a singleton at all is probably best). Some other methods are listed here.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to invoke a method of a class from another project

From Dev

How can I invoke a Processing method from outside a Processing sketch?

From Dev

python call method from outside the class

From Dev

How do you invoke a method from the same class?

From Dev

Patch a method outside python class

From Dev

Patch a method outside python class

From Dev

How can I call on a parent method from outside the class?

From Dev

How to call method outside class

From Dev

Dynamically invoke a method from a varying class

From Dev

Dynamically invoke a method from a varying class

From Dev

Invoke RFT method from java class

From Dev

invoke a method from a string as an inherited class

From Dev

If a function (that's outside of the class) needs to use a method from a class, how do I call the method?

From Dev

How to invoke a method of a groovy class from Java - Method name and parameter in string format

From Dev

How to invoke base-class method from second-level inherited class?

From Dev

Boost::Python class with function templates: How to add instances from the outside?

From Dev

How do I call outside function from class in python

From Dev

Access Class Method From Outside - React Native

From Dev

Calling a method from outside class with dependencies PHP

From Dev

python method taking information outside class

From Dev

How do I define a Python method that I only want to use in the __init__ method, i.e., that is not accessible from outside the class definition?

From Dev

Is there a "best" way to invoke a class method from a static method?

From Dev

Invoke a main class method from other class in Android

From Dev

TypeScript - How to add a method outside the class definition

From Dev

TypeScript - How to add a method outside the class definition

From Dev

How to invoke public static method for existing Java class instance from Scala?

From Dev

How to invoke static method from C# class without creating instance

From Dev

How can I invoke a method or access a field from other class in the same package in JAVA

From Dev

C# - How to invoke WCF callback calls from outside the service

Related Related

  1. 1

    How to invoke a method of a class from another project

  2. 2

    How can I invoke a Processing method from outside a Processing sketch?

  3. 3

    python call method from outside the class

  4. 4

    How do you invoke a method from the same class?

  5. 5

    Patch a method outside python class

  6. 6

    Patch a method outside python class

  7. 7

    How can I call on a parent method from outside the class?

  8. 8

    How to call method outside class

  9. 9

    Dynamically invoke a method from a varying class

  10. 10

    Dynamically invoke a method from a varying class

  11. 11

    Invoke RFT method from java class

  12. 12

    invoke a method from a string as an inherited class

  13. 13

    If a function (that's outside of the class) needs to use a method from a class, how do I call the method?

  14. 14

    How to invoke a method of a groovy class from Java - Method name and parameter in string format

  15. 15

    How to invoke base-class method from second-level inherited class?

  16. 16

    Boost::Python class with function templates: How to add instances from the outside?

  17. 17

    How do I call outside function from class in python

  18. 18

    Access Class Method From Outside - React Native

  19. 19

    Calling a method from outside class with dependencies PHP

  20. 20

    python method taking information outside class

  21. 21

    How do I define a Python method that I only want to use in the __init__ method, i.e., that is not accessible from outside the class definition?

  22. 22

    Is there a "best" way to invoke a class method from a static method?

  23. 23

    Invoke a main class method from other class in Android

  24. 24

    TypeScript - How to add a method outside the class definition

  25. 25

    TypeScript - How to add a method outside the class definition

  26. 26

    How to invoke public static method for existing Java class instance from Scala?

  27. 27

    How to invoke static method from C# class without creating instance

  28. 28

    How can I invoke a method or access a field from other class in the same package in JAVA

  29. 29

    C# - How to invoke WCF callback calls from outside the service

HotTag

Archive