Sockets but calling from different programs
Cameron Simpson
cs at cskk.id.au
Wed Oct 25 01:10:02 EDT 2017
On 23Oct2017 05:33, T Obulesu <obulesu.t at gmail.com> wrote:
>I'm new to python3 and scratching my head to write a program for this logic:
The tutor list might be a better place for such questions, but since we're
here...
>classA.py
>Class A:
> # class for socket communication
> basic init method that initializes port, address, connection
> method send(message):
> # for sending any message through the given port
> method receive():
> # will be keep on listening for incoming messages
>
>classB.py
>Class B:
> import the send method from class A
> send the messages from this class
>
>classC.py
>Class C:
> import the receive method from the class A
> receive all the messages from the same socket from here.
>
>Note:
> classA.py, classB.py, ClassC.py are saved in different locations.
>
>Can someone help me in writing the code and how can I create a single object
>and use it in multiple classed?
That is a pretty normal arrangement. Class A might look like this:
class A:
def __init__(self, port, address):
self.connection = ... make your connection to (address, port)
def send(self, msg):
send msg using self.connection ...
Since classes B and C seem expected to share tha same connection, the natural
thing is to set up the connection _separately_ from setting up B and C, and
pass the established connection to each.
So class B might commence:
class B:
def __init__(self, conn, ...):
self.conn = conn
... whatever other initialisation ...
def speak(self, something):
self.conn.send(something)
You'll notice here that we're _not_ importing anything about class A here.
Class B does not need to know class A's name to use it.
Because Python uses duck typing, you could pass _any_ object which has a
.send() method as "conn" to the class B setup. This allows you to write some
other class A2 with those same methods, but using some different type of
connection, and pass that in to classes B and C.
So a main programme might set things up like this:
from classA import A
from classB import B
from classC import C
conn = A(address, port)
sender = B(conn, other-stuff...)
receiver = C(conn, other-stuff...)
B.speak("foo")
and so forth.
Cheers,
Cameron Simpson <cs at cskk.id.au> (formerly cs at zip.com.au)
More information about the Python-list
mailing list