getter-setter

Is it possible to implement dynamic getters/setters in JavaScript?

[亡魂溺海] 提交于 2019-11-25 23:46:26
问题 I am aware of how to create getters and setters for properties whose names one already knows, by doing something like this: // A trivial example: function MyObject(val){ this.count = 0; this.value = val; } MyObject.prototype = { get value(){ return this.count < 2 ? \"Go away\" : this._value; }, set value(val){ this._value = val + (++this.count); } }; var a = new MyObject(\'foo\'); alert(a.value); // --> \"Go away\" a.value = \'bar\'; alert(a.value); // --> \"bar2\" Now, my question is, is it

What&#39;s the pythonic way to use getters and setters?

一世执手 提交于 2019-11-25 22:25:42
问题 I\'m doing it like: def set_property(property,value): def get_property(property): or object.property = value value = object.property I\'m new to Python, so i\'m still exploring the syntax, and i\'d like some advice on doing this. 回答1: Try this: Python Property The sample code is: class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" print("getter of x called") return self._x @x.setter def x(self, value): print("setter of x called") self._x =

Using @property versus getters and setters

不打扰是莪最后的温柔 提交于 2019-11-25 22:25:15
问题 Here is a pure Python-specific design question: class MyClass(object): ... def get_my_attr(self): ... def set_my_attr(self, value): ... and class MyClass(object): ... @property def my_attr(self): ... @my_attr.setter def my_attr(self, value): ... Python lets us to do it either way. If you would design a Python program, which approach would you use and why? 回答1: Prefer properties . It's what they're there for. The reason is that all attributes are public in Python. Starting names with an