Class and instance question
Scott David Daniels
scott.daniels at acm.org
Sun Dec 17 21:42:40 EST 2006
Colin J. Williams wrote:
> rzed wrote:
>> class T(object):
>> def __new__(self):
>> self.a = 1
>> ...
>> t = T()
>>
>> and I want to examine the 'a' attributes.
>>
>>>>> print T.a
>> 1
>>>>> 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
Or, to use a bit more revealing names:
class NewT(object):
def __new__(class_):
instance = object.__new__(class_)
instance.a = 1
return instance
You might have figured more of this out with:
>>> t = T()
>>> print repr(t)
>>> newt = NewT()
>>> print repr(newt)
>>> T.a
>>> t.a
--Scott David Daniels
scott.daniels at acm.org
More information about the Python-list
mailing list