Registered: Sep, 2005
Re: Postfix Typecast Operations
Posted: Sep 28, 2005 7:24 AM
> > That looks the same, but the meaning is completely
> > different. In what you wrote, there is no typecast,
> > calling the "minutes", "hours" and "years" accessors of
> > Fixnum objects.
> I hear you, but I think that it looks the same and the
> meaning is the same, it's just that the implementation is
It does look the same indeed, but the meaning is very different, what is done in Ruby is not a cast, or a type declaration, it's the access to a reading property. Said property (2.hours) may return an "Hour" object, but it may as well return another Fixnum, or a string, or whatever the author wanted it to return.
What Christopher wants to create here is not a property of an object, but a type declaration / typecast.
> > I can't think of any reason why you couldn't do it in
> > OO language with an open class for the numerics. It
> > just be a method on that class which constructs and
> > returns another object from self.
> *Christopher humbly admits ignorance*
> Open class, what's that? Is it a class which you can add
> methods to after it is defined?
I guess it is
> I have heard of such
> things, but I never got close to one. Which languages
> support this? Is there other names for this functionality?
Ruby allows you to "reopen" a class whenever you want, example one would be
@data = 5
o = MyClass.new
@data = value/5
o.data = 4 # o.data is an integer, 4 is too, should yield 0
And this ability is available in Python too, though a bit more difficult to use: your class is an objet, you add a new member (method) to your class.
[fixed]>>> class MyObject(object):
... def __init__(self):
... self.foo = "bar"
>>> a = MyObject()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'MyObject' object has no attribute 'setFoo'
>>> def f(self,val): # here I create my new method as a
... self.foo = val # standalone object
>>> MyObject.setFoo = f # and I bind it to my class
Python doesn't allow you to extend builtin types that way though, while ruby does:
NoMethodError: private method `test' called for 2:Fixnum
irb(main):002:0> class Fixnum
irb(main):003:1> def test
This is very powerful as it allows for easy extension of base types, but extremely dangerous since you may get collision between modules modifying base types. Handle with care
> Previously, I always automatically dismissed the idea of
> extending classes post-definition as being something
> unclean, and which would lead down the road to spaghetti
> code. Should I rethink this prejudice?
The issue is when just about everyone starts doing it, you don't end with spaggethi code but you end with unreliable standard types, which is why I think that kind of extensions should be done only when necessary and should be explicitely and extensively documented.