Assume the following code:
class NumStorage(object):
def __new__(cls, *nargs):
name = cls.__name__
parents = cls.__bases__
kwargs = {'num%i' % pos : i for pos, i in enumerate(nargs, 1)}
if any(kwargs.values()) and len(kwargs.values()) >= 2:
end = len(kwargs.values()) + 1
kwargs['num%i' % end] = sum(kwargs.values())
self = type(name, parents, kwargs)
return self
This NumStorage
object takes in an arbitrary amount of numbers, and if there are two or more numbers and their sum adds up to something greater than 0, then it creates a new kwarg
key.
If the initialization of the instance of NumStorage can happen in __new__
then why on earth does python even need an __init__
? Another thing that's confusing me; if we do add an __init__
method to the NumStorage
class as so:
class NumStorage(object):
def __new__(cls, *nargs):
name = cls.__name__
parents = cls.__bases__
kwargs = {'num%i' % pos : i for pos, i in enumerate(nargs, 1)}
if any(kwargs.values()) and len(kwargs.values()) >= 2:
end = len(kwargs.values()) + 1
kwargs['num%i' % end] = sum(kwargs.values())
self = type(name, parents, kwargs)
return self
def __init__(self, *nargs):
print("initializing")
It never prints "initializing" even though the __init__
should be called after __new__
since __new__
returned an instance of the object, no? If not, what is it I'm getting confused with?