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

Question:

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?

 File "C:UsersSangHyeokPycharmProjectsudp_class_testudp_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.

Asked By: user22458365

||

Answers:

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
Answered By: iowzfe
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.