Questions tagged [magic-methods]

Magic methods are implicitly invoked by a programming language when some event or language construct is used.

616 questions
59
votes
10 answers

Where is the Python documentation for the special methods? (__init__, __new__, __len__, ...)

Where is a complete list of the special double-underscore/dunder methods that can be used in classes? (e.g., __init__, __new__, __len__, __add__)
mk12
  • 25,873
  • 32
  • 98
  • 137
52
votes
1 answer

How to overload Python's __bool__ method in 2.x?

I thought this should print "False", why is it printing "True"? >>> class Foo(object): ... def __bool__(self): ... return False ... >>> f = Foo() >>> if f: ... print "True" ... else: ... print "False" ... True >>>
dividebyzero
  • 1,243
  • 2
  • 9
  • 17
47
votes
5 answers

Use of PHP Magic Methods __sleep and __wakeup

What is the use of the __sleep and __wakeup magic methods in PHP? I read the PHP documentation but it's still not clear: class sleepWakeup { public function __construct() { // constructor // } public function __sleep() { …
Madan Sapkota
  • 25,047
  • 11
  • 113
  • 117
40
votes
7 answers

PHP 5.3 Magic Method __invoke

This topic expands on When do/should I use __construct(), __get(), __set(), and __call() in PHP? which talks about the __construct, __get and __set magic methods. As of PHP 5.3 there is a new Magic Method called __invoke. The __invoke method is…
user83632
37
votes
4 answers

Are Magic Methods Best practice in PHP?

Are Magic Methods Best practice in PHP?
OM The Eternity
  • 15,694
  • 44
  • 120
  • 182
35
votes
2 answers

Is it possible, using PHPUnit mock objects, to expect a call to a magic __call() method?

I've got a mock object in a test. The real object, PageRepository, implements a magic method using __call(), so if you call $pageRepository->findOneByXXXX($value_of_field_XXXX), it will search the database for records matching that parameter. Is…
Jeremy Warne
  • 3,437
  • 2
  • 30
  • 28
31
votes
2 answers

Why does calling Python's 'magic method' not do type conversion like it would for the corresponding operator?

When I subtract a float from an integer (e.g. 1-2.0), Python does implicit type conversion (I think). But when I call what I thought was the same operation using the magic method __sub__, it suddenly does not anymore. What am I missing here? When I…
30
votes
6 answers

Why does print(t) error if t.__str__() returns a non-string, but not print(t.__str__())?

I am trying to understand the __str__ method in Python. class Test: def __str__(self): return 5 t = Test() print(t.__str__()) In this method it returns an integer value but the print method is able to print it. But, when I tried…
30
votes
6 answers

__new__ method giving error object.__new__() takes exactly one argument (the type to instantiate)

why the following code is giving error? class Foo: def __new__(cls, *args, **kwargs): print("Creating Instance") instance = super(Foo, cls).__new__(cls,*args, **kwargs) return instance def __init__(self, a, b): …
Danish Mahmood
  • 487
  • 1
  • 4
  • 9
27
votes
1 answer

Which Python dunder/magic methods do you need to implement to correctly proxy an object?

I'm trying to create an object proxy. Attribute/property lookup can be done by simply implementing the __getattribute__, __setattr__ and __delattr__ methods. However, other functionalities like len(x), x[], bool(x) require other dunder methods like…
26
votes
3 answers

Is there a way to return a custom value for min and max in Python?

I have a custom class, class A: def __init__(self, a, b): self.a = a self.b = b The class is not iterable or indexable or anything like that. If at all possible, I would like to keep it that way. Is it possible to have something…
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
25
votes
3 answers

Python __index__ special method

>>> class Thing(object): ... def __index__(self): ... return 1 ... >>> thing = Thing() >>> list_ = ['abc', 'def', 'ghi'] >>> list_[thing] 'def' >>> dict_ = {1: 'potato'} >>> dict_[thing] # KeyError How does thing know to represent…
wim
  • 338,267
  • 99
  • 616
  • 750
25
votes
2 answers

PHP Child class Magic __isset works but __get doesn't

I have an abstract parent class Mongo_Document (from mongodb-php-odm) and an inherited class Model_ActionPlan. Mongo_Document has magic __isset and __get methods that interact with an array inside the Mongo_Document class. I am trying to use the…
Moshe Katz
  • 15,992
  • 7
  • 69
  • 116
24
votes
4 answers

Assigning vs. Defining Python Magic Methods

Consider the following abhorrent class: class MapInt: __call__ = int def __sub__(self, other): return map(self, other) __add__ = map One can then call map(int, lst) via MapInt() - lst, i.e. assert list(MapInt() -…
kg583
  • 408
  • 2
  • 8
21
votes
2 answers

How to write a static python getitem method?

What do I need to change to make this work? class A: @staticmethod def __getitem__(val): return "It works" print A[0] Note that I am calling the __getitem__ method on the type A.
Woltan
  • 13,723
  • 15
  • 78
  • 104
1
2
3
41 42