new style classes, __new__, __init__

T

Torsten Mohr

Hi,

i have some questions related to new style classes, they look
quite useful but i wonder if somebody can give me an example
on constructors using __new__ and on using __init__ ?

I just see that when using it i can't give parameters to __new__
and when i additionally define __init__ then __new__ is not
called.

So i can use __new__ only for classes whose constructors don't
have parameters?


class C2:
def __new__(self):
print "new called"
self.a = 8

def __init__(self, a):
print "init called"
self.a = a

def fct(self):
print self.a


a = C2(7)
a.fct()


This way __new__ is not called, if i remove __init__ then
there are too many parameters to __new__, if i add a parameter
to __new__ then it says that __new__ does not take arguments.


Thanks for any hints,
Torsten.
 
L

Larry Bates

Torsten said:
Hi,

i have some questions related to new style classes, they look
quite useful but i wonder if somebody can give me an example
on constructors using __new__ and on using __init__ ?

I just see that when using it i can't give parameters to __new__
and when i additionally define __init__ then __new__ is not
called.

So i can use __new__ only for classes whose constructors don't
have parameters?


class C2:
def __new__(self):
print "new called"
self.a = 8

def __init__(self, a):
print "init called"
self.a = a

def fct(self):
print self.a


a = C2(7)
a.fct()


This way __new__ is not called, if i remove __init__ then
there are too many parameters to __new__, if i add a parameter
to __new__ then it says that __new__ does not take arguments.


Thanks for any hints,
Torsten.

New style classes should be based on object:

class C2(object):

-Larry
 
T

Torsten Mohr

Hello,
This way __new__ is not called, if i remove __init__ then
there are too many parameters to __new__, if i add a parameter
to __new__ then it says that __new__ does not take arguments.

I just found an article that describes it better, this example works:

class C2(object):
def __new__(cls, a):
obj = object.__new__(cls)
print "new called"
obj.a = 8

return obj

__new__ = staticmethod(__new__)


def __init__(self, a):
print "init called"
self.a = a

def fct(self):
print self.a


a = C2(7)
a.fct()


Best regards,
Torsten.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,008
Latest member
HaroldDark

Latest Threads

Top