Hello Denis!
On Wednesday May 12 2010 14:37:54 spir ☣ wrote:
> class Integer(int): pass
> i = Integer(1)
> i.name = "one"
> print i,i.name # --> "1 one"
>
> An instance of Integer has both a value 1 and a dict. Actually, one can do
> more sophisticated things (below __new__ is needed because of some
> limitation in float):
I think it's the other way round: It is quite odd that "Integer" works without
"__new__".
> class Constant(float):
> def __new__(cls, name, value):
> obj = float.__new__(cls, value)
> obj.name = name
> return obj
> def __str__(self):
> return "%s:%s" %(self.name, float.__str__(self))
> PI = Constant("pi", 3.14)
> print PI # --> "pi:3.14"
>
> In either case, the actual numerical value is transparently stored and
> inaccessible: reason why I need to use float.__str__ to print it out. But
> there also is a dict available to store attributes.
>
> So, a question arises: does the structure representing a Constant object
> like PI have one more field? Namely for type, value *and* dict?
I think you are right. The instances of class "Constant" have a "__dict__"
while the "float" instance don't have it. And obviously the "float" instances
contain some hidden data to encode the value.
However this mechanism (or a very similar one) is available to Python
programmers too: classes with a "__slots__" declaration.
http://docs.python.org/reference/datamodel.html#slots
Instances of these classes have no "__dict__" attribute. The attributes
declared with slots are also computed attributes. This means instead of
accessing the attribute directly, the Python interpreter calls a function,
which returns the attribute. (The function, really the descriptor, is stored
in the class.)
As you can inherit from classes with a "__slots__" declaration, I think all
built in classes could be implemented elegantly with this underlying
mechanism:
- It is a mechanism for conserving memory (no "__dict__"), important for
numbers.
- It is also a mechanism for storing hidden data somewhere in the object. The
implementation available to the Python programmers is not very exciting, but
it could be used for everything.
Eike.
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor