magic-methods

Best practice: PHP Magic Methods __set and __get [duplicate]

a 夏天 提交于 2019-11-26 06:12:25
问题 This question already has answers here : Closed 8 years ago . Possible Duplicate: Are Magic Methods Best practice in PHP? These are simple examples, but imagine you have more properties than two in your class. What would be best practice? a) Using __get and __set class MyClass { private $firstField; private $secondField; public function __get($property) { if (property_exists($this, $property)) { return $this->$property; } } public function __set($property, $value) { if (property_exists($this,

PHP __get and __set magic methods

若如初见. 提交于 2019-11-26 03:28:15
问题 Unless I\'m completely mistaken, the __get and __set methods are supposed to allow overloading of the → get and set . For example, the following statements should invoke the __get method: echo $foo->bar; $var = $foo->bar; And the following should use the __set method: $foo->bar = \'test\'; This was not working in my code, and is reproducible with this simple example: class foo { public $bar; public function __get($name) { echo \"Get:$name\"; return $this->$name; } public function __set($name,

Is it possible to overload Python assignment?

 ̄綄美尐妖づ 提交于 2019-11-26 02:37:34
问题 Is there a magic method that can overload the assignment operator, like __assign__(self, new_value) ? I\'d like to forbid a re-bind for an instance: class Protect(): def __assign__(self, value): raise Exception(\"This is an ex-parrot\") var = Protect() # once assigned... var = 1 # this should raise Exception() Is it possible? Is it insane? Should I be on medicine? 回答1: The way you describe it is absolutely not possible. Assignment to a name is a fundamental feature of Python and no hooks have

Difference between __str__ and __repr__?

早过忘川 提交于 2019-11-25 21:34:52
问题 What is the difference between __str__ and __repr__ in Python? 回答1: Alex summarized well but, surprisingly, was too succinct. First, let me reiterate the main points in Alex’s post: The default implementation is useless (it’s hard to think of one which wouldn’t be, but yeah) __repr__ goal is to be unambiguous __str__ goal is to be readable Container’s __str__ uses contained objects’ __repr__ Default implementation is useless This is mostly a surprise because Python’s defaults tend to be