class Socket:
def __init__(self, ip, port, auto_connect=False):
self.ip = ip
self.port = port
self.sockfd = socket.socket()
if auto_connect:
self.connect()
@staticmethod
def connect(sockfd, ip, port):
sockfd.connect((ip, port))
@nonstaticmethod
def connect(self):
self.sockfd.connect((self.ip, self.port))
Similar to how other languages like Dlang do it where you can define functions that have the same names; but different signatures, thus allowing the compiler to distinguish what function ambiguous function calls refer to.
I had the thought that you could somehow imitate properties, because they allow for you to enact on the same function but use different inputs and receive different outputs. But since the @property
tag isn't Python, and recreating it in C isn't something very feasible nor efficient work-wise; I'm seeking a way to do it either purely or with 3rd-party libraries.
class Socket:
def __init__(self, ip, port, auto_connect=False):
self.ip = ip
self.port = port
self.sockfd = socket.socket()
if auto_connect:
self.connect()
@staticmethod
def static_connect(sockfd, ip, port):
sockfd.connect((ip, port))
def connect(self):
self.sockfd.connect((self.ip, self.port))
I did as well figure that you could just name the functions differently but I just don't like this approach since it involves the user knowing that the secondary function exists and although sensible, not my style.
Also I did suggest to myself the fact that I could do something along the lines of this:
class Socket: ... def connect(self, ip, port): """ When using statically: self = socket ip = ip port = port When using as a class member: ip = ip & port = port """
if isinstance(self, types.ClassType):
self.sockfd.connect((ip, port))
return
self.connect((ip, port))
But that's just unnatural and could cause confusion when somebody reads the code, and is over-all unPythonic.
NOTE: This function replicates behaviour shown in here but it luckily manages to utilize all the parameters and thus no optional parameters are required, so apologies for not mentioning it explicitly, but my question doesn't ask for a way to do it with key word arguments.
tl;dr:
class functions that have different signatures e.g.: static method but don't replace each other- and yet still can be called appropriately