So i am making a socket server in python and i want to use classes. The problem is that when calling setup.com_socket.recv() variable, the result can be printed, but it cannot be called. Problem is in verify.py. Here is the code:
server.py:
import socket
import threading
from verify import Verify
from setup import Setup
verify = Verify()#start the classes for use
setup = Setup()
setup.make_server()
verify.verify()
setup.py:
import socket
class Setup:
def __init__(self):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client_list: list = []
self.com_socket = ""
self.addr: int = 0
self.current_id: int = 0
def make_server(self):
self.server.bind(('localhost', 9999))
self.server.listen()
print("listening to connections")
self.com_socket, self.addr = self.server.accept()
self.client_list.append(self.com_socket)
with open('current_id.txt', 'r') as f:
self.current_id = int(f.readlines()[0].rstrip())
self.com_socket.send(str(self.current_id).encode('utf-8'))
with open('current_id.txt', 'w') as f:
f.write(str(self.current_id+1))
return True
verify.py:
from setup import Setup
setup = Setup()
class Verify:
def verify(self):
message = setup.com_socket.recv(1024).decode('utf-8')#problem is here
error is:
Traceback (most recent call last):
File "C:\whatever\server.py", line 11, in <module>
verify.verify()
File "C:\whatever\verify.py", line 9, in verify
message = setup.com_socket.recv(1024).decode('utf-8')#problem is here
AttributeError: 'str' object has no attribute 'recv'
I have not tried anything other than this, if someone could give an answer it would be very good. I will edit it if there is something missing.
to use an object inside another object the best way is to pass it in the constructor, and save it, to be later used in the methods.
class Verify:
def __init__(self, setup_obj):
self.setup_obj = setup_obj
def verify(self):
message = self.setup_obj.com_socket.recv(1024).decode('utf-8') # no problem here
and in server.py
setup = Setup()
verify = Verify(setup) # verify object will contain setup object and can use it.