Mathieson
Mathieson

Reputation: 1282

Changing an arg in __new__ is not carrying over to __init__

I am having trouble understanding what is happening here, because this is something I thought worked.

class Test(object):

    def __new__(cls, arg):
        return object.__new__(cls, 345)

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

test = Test('testing')
print
print '****', test.arg

This little example outlines the confusion I am having. Within the new function I am making it so that I pass an integer of 345 instead of my string of "testing" when creating the class. However, when I check the arg afterwards it is still my string of "testing".

At the same time, this example from the Python docs does work:

class inch(float):
    "Convert from inch to meter"
    def __new__(cls, arg=0.0):
        return float.__new__(cls, arg*0.0254)
print inch(12)

Can someone explain what the difference is here? Is there some way for me to get the functionality I am looking for?

Upvotes: 2

Views: 48

Answers (1)

chepner
chepner

Reputation: 531075

object.__new__ accepts, but ignores, any arguments other than the first class argument. This allows you to add other arguments to __new__ in a subclass without breaking calls to super().__new__.

float.__new__ is a separate function which uses its second argument to provide a value.

Upvotes: 3

Related Questions