[Tutor] __init__ for class instantiation?
Brian Almond
BAlmond@russreid.com
Wed Apr 30 12:32:01 2003
>> ZA> The problem here (as with __new__) is that __init__ will be
called
>> with ZA> every creation of a Player instance.
>>
>> It seems that you are wrong here---__new__ is called only once
after
>> class is defined.
>I created a new class, and defined __new__, but it doesn't get called
from
>Python, as far as I can tell. Here's my code:
>
>class C:
> def __new__ (cls):
> print (cls)
>
>Even when I create the first instance (d = C()), I don't get any
output.
I didn't see a response to this yet, so let me chime in.
The __new__ magic method is a feature of new-style Python classes. As
far as I know, a __new__ method defined in an old-style class is just
like any other method. (Except for the funny name :)
Try this:
class C(object):
count = 0
def __new__(cls):
C.count += 1
return object.__new__(cls)
>>> c1 = C()
>>> c1
<__main__.C object at 0x00923668>
>>> C.count
1
>>> c2 = C()
>>> c2
<__main__.C object at 0x00933A50>
>>> C.count
2
This perhaps is an odd way to use __new__ - I made this only to
demonstrate that __new__ is called for every instantiation of a
new-style class.
PS: Although there's nothing wrong with the Python docs, I really liked
the section on classes in Alex Martelli's book "Python in a Nutshell" -
it's a good reference.