Sleepy Developer

Python singleton using new-style class

The new-style class is the class that inherit from object or the new-style class.
The new-style class has __new__ method. When creating new instance, __new__ is called before __init__ and it would return the instance.

This is an example:

>>> class A(object):
...     _inst = None
...     def __new__(cls, *args, **kwargs):
...         if cls._inst is not None:
...             return cls._inst
...         cls._inst = object.__new__(cls, *args, **kwargs)
...         return cls._inst
...
>>> c = A()
>>> id(c)
142024844
>>> b = A()
>>> id(b)
142024844
>>> c.x = 1
>>> b.x
1
>>>

Python UDP Client

This is very simple UDP client send data to 192.168.1.102.

from socket import socket, AF_INET, SOCK_DGRAM
data = 'UDP Data Content'
port = 26900
hostname = '192.168.1.102'
udp = socket(AF_INET,SOCK_DGRAM)
udp.sendto(data, (hostname, port))

Author:

  • nattapon

Archives:

Powered by Django.