Class and instance question

Colin J. Williams cjw at sympatico.ca
Sun Dec 17 12:01:50 EST 2006


rzed wrote:
> I'm confused (not for the first time). 
> 
> I create these classes:
> 
> class T(object):
>     def __new__(self):
>         self.a = 1
> 
> class X(T):
>     def __init__(self):
>         self.a = 4
> 
> class Y:
>     def __init__(self):
>         self.a = 4
> 
> class Z(object):
>     def __init__(self):
>         self.a = 4
> 
> 
> ... and these instances:
> 
> t = T()
> x = X()
> y = Y()
> z = Z()
> 
> and I want to examine the 'a' attributes.
> 
>>>> print T.a
> 1
>>>> print y.a
> 4
>>>> print z.a
> 4
> 
> So far, it's as I expect, but:
> 
>>>> print x.a
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'NoneType' object has no attribute 'a'
> 
>>>> print t.a
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'NoneType' object has no attribute 'a'
> 
> So what the heck is 'T'? It seems that I can't instantiate it or 
> derive from it, so I guess it isn't a proper class. But it's 
> something; it has an attribute. What is it? How would it be used 
> (or, I guess, how should the __new__() method be used)? Any hints?
> 
__new__ should return something.  Since there is no return statement, 
None is returned.

You might try something like:

class T(object):
   def __new__(cls):
     cls= object.__new__(cls)
     cls.a= 1
     return cls
t= T()
print t.a

Colin W.




More information about the Python-list mailing list