During a bout of C# and WPF recently, I got to like C#'s properties:
public double length_inches
{
get { return length_metres * 39.0; }
set { length_metres = value/39.0; }
}
Noticing, of course, that length_metres may change from being a field to a property, and the code need not care. WPF can also bind UI elements to object properties very happily.
When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.
Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.
The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it?
Python definitely supports properties:
class Foo(object):
def get_length_inches(self):
return self.length_meters * 39.0
def set_length_inches(self, val):
self.length_meters = val/39.0
length_inches = property(get_length_inches, set_length_inches)
Starting in Python 2.5, syntactic sugar exists for read-only properties, and in 2.6, writable ones as well:
class Foo(object):
# 2.5 or later
@property
def length_inches(self):
return self.length_meters * 39.0
# 2.6 or later
@length_inches.setter
def length_inches(self, val):
self.length_meters = val/39.0
In JavaScript:
var object = {
// .. other property definitions ...
get length_inches(){ return this.length_metres * 39.0; },
set length_inches(value){ this.length_metres = value/39.0; }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With