__init__ function problem

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Tue Nov 7 09:39:05 EST 2006


On Tue, 07 Nov 2006 05:26:07 -0800, kelin,zzf818 at gmail.com wrote:

> Hi,
> 
> Today I read the following sentences, but I can not understand what
> does the __init__ method of a class do?

Play around with this class and see if it helps:


class MagicStr(str):
	"""Subclass of str with leading and trailing asterisks."""
	def __new__(cls, value=''):
		print "Calling subclass constructor __new__ ..."
		# Construct a MagicStr object.
		obj = super(MagicStr, cls).__new__(cls, '***' + value + '***')
		print "  - inspecting constructor argument:"
		print "    value, id, type:", value, id(value), type(value)
		print "  - inspecting constructor result:"
		print "    value, id, type:", obj, id(obj), type(obj)
                # Create the instance, and call its __init__ method.
		return obj 
	def __init__(self, value):
		print "Calling subclass __init__ ..."
		print "  - inspecting __init__ argument:"
		print "    value, id, type:", value, id(value), type(value)
		print "Done."


Notice that when __new__ is called, the instance doesn't exist yet, only
the class, so the first argument for __new__ is the class, not the
instance.



> __init__ is called immediately after an instance of the class is
> created. It would be tempting but incorrect to call this the
> constructor of the class. It's tempting, because it looks like a
> constructor (by convention, __init__ is the first method defined for
> the class), acts like one (it's the first piece of code executed in a
> newly created instance of the class), 

That's not quite true. For new-style classes __new__ is called before
__init__, as you can see from the MagicStr class above.


> and even sounds like one ("init"
> certainly suggests a constructor-ish nature). Incorrect, because the
> object has already been constructed by the time __init__ is called, and
> you already have a valid reference to the new instance of the class.
> But __init__ is the closest thing you're going to get to a constructor
> in Python, and it fills much the same role.

This is true for old-style classes.
 
> It says the __init__ is called immediately after an instance of the
> class is created. What dose "immediately" mean?

Once the __new__ method creates the instance and returns, before anything
else happens, the instance's __init__ method is called.



-- 
Steven.




More information about the Python-list mailing list