adarsh
adarsh

Reputation: 6978

How to have multiple ways to construct an object of same class in python?

For example,

I have my class, MyClass

and I want to be able to instantiate it as MyClass((1, 2)) but MyClass(1, 2) should also result in the same. Is it also possible to instantiate it by writing MyClass[1, 2] by some way?

Upvotes: 0

Views: 76

Answers (2)

NPE
NPE

Reputation: 500227

No, you can't do that in any half-sane way. The nearest thing syntactically that I can think of is:

class X(object):
  def __init__(self, x, y):
   print x, y

X(1, 2)
X(*(1, 2))
X(*[1, 2])

There are some legitimate uses for this. However, they are pretty limited.

Upvotes: 2

user2357112
user2357112

Reputation: 280291

def __init__(arg1, arg2=None):
    if arg2 is None:
        construct_one_way()
    else:
        do_something_different()

You can technically get MyClass[1, 2] to work with a custom metaclass, but anyone reading your code will hate you. Brackets are for element access.

If you want to be That Guy With The Unmaintainable Code, here's the metaclass option:

class DontDoThis(type):
    def __getitem__(self, arg):
        return self(arg)

class SeriouslyDont(object):
    __metaclass__ = DontDoThis
    def __init__(self, arg1, arg2=None):
        if arg2 is None:
            arg1, arg2 = arg1
        self.arg1 = arg1
        self.arg2 = arg2

Demonstration:

>>> SeriouslyDont[1, 2]
<__main__.SeriouslyDont object at 0x000000000212D0F0>

Upvotes: 5

Related Questions