The getattr() function returns the value of the specified attribute from the specified object.
Python getattr() The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.
__getattr__Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self).
Python | getattr() method Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key. Parameters : obj : The object whose attributes need to be processed.
It's now possible if your browser has support for the ES6 Proxy feature. You can check this in the ECMAScript 6 compatibility table.
If you have the proxy support, you would use it as follows:
let handler = {
get(target, name) {
return `Value for attribute ${name}`
}
}
let x = new Proxy({}, handler);
console.log(x.lskdjoau); // produces message: "Value of attribute 'lskdjoau'"
Works in chrome, firefox, and node.js. Downsides: doesn't work in IE - freakin IE. Soon.
Sadly the answer is No. See Python's __getattr__ in Javascript
You've got __defineGetter__
, but as you noted you need to know the name of the attribute you will be accessing.
By the way I think you meant __getattr__
(__getitem__
is for things you want to access with []
).
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