Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I create a class in Python that contains a udp socket?

I created a class that acts as a UDP server on port 1500

import socket

class Udp_Server():
    def __int__(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind(("", 1500))

    def recv_udp(self):
        data, addr = self.sock.recvfrom(1024)
        return data, addr

In main, I call the recv_udp function with the class I created as below

from  udp_server import Udp_Server

udp_server = Udp_Server()
data, addr = udp_server.recv_udp()

However, the following error occurs.
The development environment is python 3.11.
How could i fix this problem?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 File "C:\Users\SangHyeok\PycharmProjects\udp_class_test\udp_server.py", line 9, in recv_udp
    data, addr = self.sock.recvfrom(1024)
                 ^^^^^^^^^
AttributeError: 'Udp_Server' object has no attribute 'sock'
python-BaseException

Process finished with exit code 1

Using a socket right from main takes care of the problem. But I want to include udp socket inside the class.

>Solution :

The problem with your code is a mistake in the Udp_Server class’s constructor. You defined the constructor with __int__ rather than __init__. As a result, the sock attribute is not initialized, resulting in the error Udp_Server object has no attribute sock . To resolve this issue, modify __int__ to __init__ in your class declaration as follows:

import socket

class Udp_Server():
    def __init__(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind(("", 1500))

    def recv_udp(self):
        data, addr = self.sock.recvfrom(1024)
        return data, addr
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading