0

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?

0

2 Answers 2

5
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>
Sign up to request clarification or add additional context in comments.

5 Comments

Love the cleverness, but seriously hope this won't make it into any sort of real-world code! :-)
@JonClements: Wait, +2 - (-1) is +3 :)
The English language use of the hyphen... etc... @NPE :)
@JonClements: I'll buy that. :) Anyway, bedtime. Night-night.
Thank you for the well documented warnings :)
2

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.

4 Comments

Of course this would work, but this is not I'm looking for. I'm not sure but maybe metaclasses seem that it might help and I've been reading up on them but I can't quite figure out how
@adarsh then what perverse language evasion are you looking for?
I am looking for something that makes more intuitive sense for representing mathematical intervals
@adarsh: In which case presumably you'd also want to represent half-open intervals? That would be a complete non-starter...

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.