As I transition from JavaScript to Python, I noticed I haven't figured out a way to add properties to the data type classes.
For example, in JavaScript, if I wanted to be able to type arr.last
and have it return the last element in the array arr
, or type arr.last = 'foo'
and to set the last element to 'foo'
, I would use:
Object.defineProperty(Array.prototype,'last',{
get:function(){
return this[this.length-1];
},
set:function(val){
this[this.length-1] = val;
}
});
var list = ['a','b','c'];
console.log(list.last); // "c"
list.last = 'd';
console.log(list); // ["a","b","d"]
However, in Python, I'm not sure how to do the equivalent of Object.defineProperty(X.prototype,'propname',{get:function(){},set:function(){}});
Note: I am not asking for how to do the specific example function, I am trying to be able to define a property with a get
and set
onto the primitive data types (str, int, float, list, dict, set, etc.)