magic-methods

I am attempting to print only a selected amount of Pi, it returns with an error of "Decimal has no attribute: __getitem__

主宰稳场 提交于 2019-11-27 08:54:23
问题 def pi(): prompt=">>> " print "\nWARNING: Pi may take some time to be calculated and may not always be correct beyond 100 digits." print "\nShow Pi to what digit?" n=raw_input(prompt) from decimal import Decimal, localcontext with localcontext() as ctx: ctx.prec = 10000 pi = Decimal(0) for k in range(350): pi += (Decimal(4)/(Decimal(8)*k+1) - Decimal(2)/(Decimal(8)*k+4) - Decimal(1)/(Decimal(8)*k+5) - Decimal(1)/(Decimal(8)*k+6)) / Decimal(16)**k print pi[:int(n)] pi() Traceback (most recent

Making a python user-defined class sortable, hashable

时光怂恿深爱的人放手 提交于 2019-11-27 07:55:57
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? I almost posted this as a comment to the other answers but it's really an answer in and of itself. To make your items sortable,

__get/__set/__call performance questions with PHP

徘徊边缘 提交于 2019-11-27 07:01:39
问题 I have a custom-built MVC PHP framework that I am in the process of rewriting and had a question about performance and magic methods. With the model portion of the framework, I was thinking if __get / __set magic methods would cause too much performance hit to be worth using. I mean accessing (reads and writes) model data is going to be one of the most common things performed. Is the use of __get / __set magic methods too big of a performance hit for heavy use functionality like the model

Why does Python use 'magic methods'?

旧时模样 提交于 2019-11-27 06:06:18
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 haven't worked out what they are yet. AFAIK, len is special in this respect and has historical roots. Here

PHP - Indirect modification of overloaded property

一曲冷凌霜 提交于 2019-11-26 22:26:31
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'); $user->role->rolename; This works so far. The User object doesn't have a property called 'role', so it uses

Python __call__ special method practical example

偶尔善良 提交于 2019-11-26 21:14:56
I know that __call__ method in a class is triggered when the instance of a class is called. However, I have no idea when I can use this special method, because one can simply create a new method and perform the same operation done in __call__ method and instead of calling the instance, you can call the method. I would really appreciate it if someone gives me a practical usage of this special method. Django forms module uses __call__ method nicely to implement a consistent API for form validation. You can write your own validator for a form in Django as a function. def custom_validator(value):

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

ぃ、小莉子 提交于 2019-11-26 19:42:42
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 conversion going on here, similar to the implicit type conversions in the Predef object (but different in

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

戏子无情 提交于 2019-11-26 19:20:22
>>> 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 <attribute '__dict__' of 'A' objects> found in A.__dict__.__dict__ , and when does it contain something? Rosh Oxymoron First of

How does python numpy.where() work?

狂风中的少年 提交于 2019-11-26 19:10:19
问题 I am playing with numpy and digging through documentation and I have come across some magic. Namely I am talking about numpy.where() : >>> x = np.arange(9.).reshape(3, 3) >>> np.where( x > 5 ) (array([2, 2, 2]), array([0, 1, 2])) How do they achieve internally that you are able to pass something like x > 5 into a method? I guess it has something to do with __gt__ but I am looking for a detailed explanation. 回答1: How do they achieve internally that you are able to pass something like x > 5

How to document magic (_call and _callStatic) methods for IDEs

久未见 提交于 2019-11-26 19:07:08
问题 After many happy years coding in notepad++ and sublime, I've been advised to give a PHP IDE a go. I'm trying out phpStorm and it seems nice. The code completion and documentation is a great feature but isn't working out for me when magic methods are used. Is there a work around to get phpStorm to understand what's going on in magic methods? Our situation is something like this: abstract class a { public static function __callStatic($method,$args) { if(strpos($method,"get_by_") === 0) { //do