1

So I am aware that class methods can be used to "overload" the init method in python, but I'm running into a bit of a problem. Say, for example, I have a constructor like this:

def __init__(self, serviceName, endpoint, exportedInterface, exportedObject, remoteObjectInterface, remoteObjectProxy,
                interruptionHandler, invalidationHandler):

    self._serviceName = serviceName;
    #etc.

@classmethod
def createConnection(cls, serviceName):
    return cls(serviceName, None, None, None, None, None, None, None)

Do I really have to list out a value for every single data member in the class method, just to create an instance of the class with a class method? Also, I plan to add more data members to the class later on, but I'm not to happy about having this unwieldy init function with like 15 arguments. Is there a better way to go about this?

2 Answers 2

6

You can use default values for the parameters. Then you can specify which one you want to replace.

def __init__(self, serviceName, endpoint = None, exportedInterface = None, 
             exportedObject = None, remoteObjectInterface = None, remoteObjectProxy = None,
             interruptionHandler = None, invalidationHandler = None):

    self._serviceName = serviceName;
    #etc.

@classmethod
def createConnection(cls, serviceName):
    return cls(serviceName)

Now you can set only some arguments like this (the other will use their default values):

@classmethod
def createConnectionWithInterruptionHandler(cls, serviceName, interruptionHandler):
    return cls(serviceName, interruptionHandler=interruptionHandler)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This helps :)
0

Two options are:

Use keyword arguments. e.g.

def __init__(self, **kwargs):
    for names in ("serviceName", ...):
        setattr(self, "_" + name, kwargs.get(names, None))

Make __init__ do the bare minimum and use factory functions to do the appropriate initialization

def __init__(self): pass

@classmethod
def createConnection(cls, serviceName):
    foo = cls()
    foo._serviceName = serviceName
    return foo

2 Comments

why are you using __setitem__ directly instead of self["_"+name] = kwargs.get(names)? Or do you maybe mean to use setattr instead?
@Tadhg: Yes, I meant setattr

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.