'Why __init__ doesn't execute after adding metaclass to a class?

For the code below

class C:

    def __new__(cls, *args, **kwargs):
        return super().__new__(cls)

    def __init__(self, data):
        self.data = data

    def __str__(self):
        return f'<C {self.data}>'


print(C(30))
print(C('hello, world'))

I can get the result

<C 30>
<C hello, world>

Now I try to add a metaclass to class C like below:

class P(type):
    def __call__(cls, data):
        if isinstance(data, int):
            return data
        else:
            return cls.__new__(cls, data)


class C(metaclass=P):
    def __new__(cls, *args, **kwargs):
        return super().__new__(cls)

    def __init__(self, data):
        self.data = data

    def __str__(self):
        return f'<C {self.data}>'


print(C(30))
print(C('hello, world'))

This time when execute print(C('hello, world')) I get an exception as:

AttributeError: 'C' object has no attribute 'data'

Seems that the C object was created but the __init__ method was skipped. Can anybody tell me why?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source