You can override __new__()
:
class test(object):
def __new__(cls, x, y):
return x+y
z = test(1, 2)
print z # => 3
That said, I can not stress enough how incredibly pointless doing so is, more or less always.
While we're being pointless, you can also have sum()
be a method:
class test(object):
def __new__(cls, *args, **kwargs):
test_obj = super(test, cls).__new__(cls)
test_obj.__init__(*args, **kwargs)
return test_obj.sum()
def __init__(self, x, y):
test.x = x
test.y = y
def sum(self):
return self.x + self.y
z = test(1, 2)
print z
However, there's no way to access it outside the __new__
implementation. Or without creating a test
instance "the hard way" by manually invoking object.__new__()
and __init__
, at which point any violence you'd suffer at the hands of your supervisor would be justified.
To maximise perversion, here's @kindall's suggested variant – needlessly overengineered of course:
With a metaclass
class meta_delegate(type):
def __call__(cls, *args, **kwargs):
obj = cls.__new__(cls)
obj.__init__(*args, **kwargs)
delegate = cls.__delegate
if (isinstance(delegate, basestring)):
delegate = getattr(obj, delegate)
return delegate()
else:
return delegate(obj)
@staticmethod
def to(delegate):
def __new__(*args, **kwargs):
cls = meta_delegate(*args, **kwargs)
cls.__delegate = delegate
return cls
return __new__
class test(object):
def __init__(self, x, y):
test.x = x
test.y = y
def sum(self):
return self.x + self.y
__metaclass__ = meta_delegate.to(sum)
I'm actually honestly surprised it works. It seems that invoking a metaclass doesn't use its __call__
.
And a last one just to illustrate the sheer pointlessness of it all:
So pointless it's circular
class meta_delegate(type):
def __call__(cls, *args, **kwargs):
return cls.__delegate(*args, **kwargs)
@staticmethod
def to(delegate):
def __new__(*args, **kwargs):
cls = meta_delegate(*args, **kwargs)
cls.__delegate = staticmethod(delegate)
return cls
return __new__
class test(object):
__metaclass__ = meta_delegate.to(lambda x, y: x+y)
The delegate here can be any callable, and the API is much simpler! Now if you'll excuse me I'll go and have a drink.