magic-methods

Why does Python use 'magic methods'?

↘锁芯ラ 提交于 2019-11-26 17:34:37
问题 I've been playing around with Python recently, and one thing I'm finding a bit odd is the extensive use of 'magic methods', e.g. to make its length available, an object implements a method, def __len__(self) , and then it is called when you write len(obj) . I was just wondering why objects don't simply define a len(self) method and have it called directly as a member of the object, e.g. obj.len() ? I'm sure there must be good reasons for Python doing it the way it does, but as a newbie I

Which special methods bypasses __getattribute__ in Python?

安稳与你 提交于 2019-11-26 16:31:32
问题 In addition to bypassing any instance attributes in the interest of correctness, implicit special method lookup generally also bypasses the __getattribute__() method even of the object’s metaclass. The docs mention special methods such as __hash__ , __repr__ and __len__ , and I know from experience it also includes __iter__ for Python 2.7. To quote an answer to a related question: "Magic __methods__() are treated specially: They are internally assigned to "slots" in the type data structure to

Making a python user-defined class sortable, hashable

孤者浪人 提交于 2019-11-26 13:54:56
问题 What methods need to be overridden/implemented when making user-defined classes sortable and/or hashable in python? What are the gotchas to watch out for? I type dir({}) into my interpreter to get a list of methods on built-in dicts. Of those, I assume I need to some implement some subset of ['__cmp__', '__eq__', '__ge__', '__gt__', '__hash__', '__le__', '__lt__', '__ne__'] Is there a difference in which methods must be implemented for Python3 as opposed to Python2? 回答1: I almost posted this

Is it possible to overload Python assignment?

时间秒杀一切 提交于 2019-11-26 11:22:25
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? The way you describe it is absolutely not possible. Assignment to a name is a fundamental feature of Python and no hooks have been provided to change its behavior. However, assignment to a member in a class instance can be controlled as

PHP __get and __set magic methods

风格不统一 提交于 2019-11-26 10:23:35
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, $value) { echo "Set:$name to $value"; $this->$name = $value; } } $foo = new foo(); echo $foo->bar; $foo-

Assigning (instead of defining) a __getitem__ magic method breaks indexing [duplicate]

送分小仙女□ 提交于 2019-11-26 10:03:15
问题 This question already has answers here : Why won't dynamically adding a `__call__` method to an instance work? (2 answers) Closed 11 months ago . I have a wrapper class similar to this (strongly simplified) example: class wrap(object): def __init__(self): self._data = range(10) def __getitem__(self, key): return self._data.__getitem__(key) I can use it like this: w = wrap() print w[2] # yields \"2\" I thought I could optimize and get rid of one function call by changing to this: class wrap

PHP - Indirect modification of overloaded property

大兔子大兔子 提交于 2019-11-26 08:19:59
问题 I know this question has been asked several times, but none of them have a real answer for a workaround. Maybe there\'s one for my specific case. I\'m building a mapper class which uses the magic method __get() to lazy load other objects. It looks something like this: public function __get ( $index ) { if ( isset ($this->vars[$index]) ) { return $this->vars[$index]; } // $index = \'role\'; $obj = $this->createNewObject ( $index ); return $obj; } In my code I do: $user = createObject(\'user\')

How does Scala's apply() method magic work?

北战南征 提交于 2019-11-26 07:25:18
问题 In Scala, if I define a method called apply in a class or a top-level object, that method will be called whenever I append a pair a parentheses to an instance of that class, and put the appropriate arguments for apply() in between them. For example: class Foo(x: Int) { def apply(y: Int) = { x*x + y*y } } val f = new Foo(3) f(4) // returns 25 So basically, object(args) is just syntactic sugar for object.apply(args) . How does Scala do this conversion? Is there a globally defined implicit

scala slick method I can not understand so far

六眼飞鱼酱① 提交于 2019-11-26 06:55:47
问题 I try to understand some Slick works and what it requires. Here it an example: package models case class Bar(id: Option[Int] = None, name: String) object Bars extends Table[Bar](\"bar\") { def id = column[Int](\"id\", O.PrimaryKey, O.AutoInc) // This is the primary key column def name = column[String](\"name\") // Every table needs a * projection with the same type as the table\'s type parameter def * = id.? ~ name <>(Bar, Bar.unapply _) } Could somebody explain me what\'s the purpose of *

What is the __dict__.__dict__ attribute of a Python class?

試著忘記壹切 提交于 2019-11-26 06:13:52
问题 >>> class A(object): pass ... >>> A.__dict__ <dictproxy object at 0x173ef30> >>> A.__dict__.__dict__ Traceback (most recent call last): File \"<string>\", line 1, in <fragment> AttributeError: \'dictproxy\' object has no attribute \'__dict__\' >>> A.__dict__.copy() {\'__dict__\': <attribute \'__dict__\' of \'A\' objects> ... } >>> A.__dict__[\'__dict__\'] <attribute \'__dict__\' of \'A\' objects> # What is this object? If I do A.something = 10 , this goes into A.__dict__ . What is this