Questions tagged [magic-methods]
Magic methods are implicitly invoked by a programming language when some event or language construct is used.
537
questions
0
votes
0answers
12 views
Can anyone please tell me how this code works?
class SpecialString:
def __init__(self, cont):
self.cont = cont
def __truediv__(self, other):
line = "=" * len(other.cont)
return "\n".join([self....
1
vote
1answer
44 views
Bracket assignment in Python
I would like to create a class that is able to do the following
class Test:
# code here
test = Test()
test["test"] = 1
test.test # returns 1
Is this possible in Python using magic ...
0
votes
3answers
31 views
How to make a Python class properties accesible by index?
I have a Django model like this:
class Competitor(models.Model):
"""
Competitor model object
"""
name = models.CharField(max_length=20)
easy = ArrayField(models....
3
votes
1answer
51 views
Python Data Model, Type Protocols, & Magic Methods
Is there a "mind map", UML diagram, graphic, or some solid reference for the different python types and the magic methods they must implement?
I'm using Python 3.8. The data model docs and ...
2
votes
1answer
64 views
Different return types, overloading __add__
I wish to implement something like the following. There is a class foo which contains a list of infoo objects. I was thinking that in order to overload the __add__ operator I should
class foo(object):
...
1
vote
0answers
19 views
Having trouble to understand how __str__ special method executes
I am not able to explain the behaviour of the following code when running it in PyCharm:
class Empty:
def __init__(self):
pass
def __str__(self):
print('in!')
return f'...
0
votes
1answer
75 views
len() vs __len__: TypeError: 'float' object cannot be interpreted as an integer
I met a weird bug and I don't think it's my code's problem.
Here are the objects I have got:
Boundary: represents domain and range, such that [1, 10], it has a low attribute and a high attribute, in ...
0
votes
0answers
21 views
Why does overwriting `__str__` of an object at runtime not work? [duplicate]
Given the following interactive Python interpreter session:
>>> class c(object): pass
>>> o=c()
>>> str(o)
'<__main__.c object at 0x7f865da68820>'
>>> o....
0
votes
1answer
47 views
use a Magic Methods in an other Magic Methods
class Juice:
def __init__(self, name, capacity):
self.name = name
self.capacity = capacity
def __str__(self):
return (self.name + ' ('+str(self.capacity)+'L)')
def ...
1
vote
1answer
25 views
Class comparisons (like __ge__) without functools total_ordering
The following code works, but surprisingly also for the methods that have not been implemented.
Normally you need total_ordering to accomplish this, right?
class Account:
def __init__(self, ...
7
votes
1answer
141 views
How is Python's iterator unpacking (star unpacking) implemented (or, what magic methods are involved in unpacking a custom iterator?)
I am writing a class that defines __iter__ and __len__, where the value of __len__ depends on the iterator returned by __iter__. I am getting an interesting RecursionError.
Language versions: Python 3....
0
votes
1answer
31 views
What use is there for defining magic methods outside of a class?
What happens if I define a magic method outside a class?
For example, say I do:
def __str__(stuff):
return "chicken"
directly inside the module.
When would something like this be useful?...
0
votes
1answer
34 views
Comparing values with __eq__ in Python
Good day/night, I'm new to Python and I'm making a class called Alpharange that works like the range function but with capital letters only. While I was testing to see if the class worked or not I ...
2
votes
3answers
50 views
python: reverse the elements of magic methods that affect operators [duplicate]
i am trying, just for exercise, to create a python object that can contain a number with arbitrary decimals. Everything works fine but i'm having problems with making the object interact with ...
0
votes
1answer
25 views
Does “if” have implicit access to a class’s special methods even when they are not directly called?
I don’t understand how the code in the for loop knows whether the instance of the class is truthy or not. My understanding is probably faulty but what I think is happening is this: the call to bool ...
0
votes
0answers
20 views
getting an error = TypeError: 'str' object cannot be interpreted as an integer . I am learning methods in python and I am having this problem
what is the problem here pls help. What am I doing wrong here
class Name:
def __init__(self,first,last):
self.first = first
self.last = last
def __len__(self):
return self....
0
votes
0answers
39 views
Laravel local scope intellisense
i'm using local scope functions in laravel (https://laravel.com/docs/8.x/eloquent#local-scopes)
Especially i'm using laravel_ide_helper 4.3.2 and laravel 5.3 (Updating is not an option)
Let's say i ...
0
votes
1answer
49 views
Class __str__ magic-methods
Hi I am learning classes and special methods and I having trouble with the code below, as I cant seem to figure out how to get the def __ str__ to work, it prints none
class Circle:
def __init__(...
0
votes
0answers
17 views
Double Behavior Of Magic Methods __set() and __get() with property_exists() function and without it
I am trying to understand Magic functions in a class and while I was testing __set() and __get() methods.
CODE:
class kids{
private $height;
public function __set($property, $value){
//if(...
0
votes
2answers
160 views
Fatal error: Declaration of Foo::__toString(): void must be compatible with Stringable::__toString(): string
After upgrading to PHP 8 I'm now seeing this Fatal error what's wrong with my code ? And what is this Stringable?
1
vote
0answers
31 views
Is a way to implement a double index into a special method Python? [duplicate]
I am currently trying to implement a Sudoku solver where I have created a 9x9 board and a dictionary object sDict that contains all candidate sets for each position in the board. Before adding to the ...
0
votes
0answers
26 views
Reverse order of Composition in Python Permutation Class
In this class https://github.com/jwodder/permutation/blob/master/permutation.py composition of permutations is performed from right to left, as defined in this method:
def __mul__(self, other):
&...
-2
votes
2answers
52 views
Python data model / internal methods
I would like to understand the data model in python (3.8.2), so maybe someone can explain in simple words, why every basic data type is a class-object and has so many attributes and functions.
...
0
votes
2answers
46 views
referencing __init__.__kwdefaults__ vs explicitly writing a dictionary [duplicate]
python 3, new to coding and python.
i built a class dictionary with default values, then attempted to build a nested dictionary based on that class dictionary and encountered unexpected behaviour:
...
0
votes
1answer
44 views
python __call__ magic method is class method or object method?
I'm recently working on design patterns in python and I saw this in the singleton design pattern:
# THIS WILL BE USED AS METACLASS FOR OTHER CLASSES
class MetaSingleton(type):
_instance = {}
...
1
vote
2answers
263 views
Can I change the default __add__ method in Python?
Is it possible to change the default __add__ method to do something else than just add?
For example, if the goal is with this line:
5+5 get The answer is 10 or anything else like 0 by changing __add__ ...
0
votes
0answers
74 views
Implement abstractmethod using the __getattr__ dunder method
I have a class that implements an interface, but I don't want to explicitly implement some of the methods. So I am using __getattr__ dunder method for these methods, However I receive a TypeError when ...
-3
votes
1answer
74 views
Are dunders methods or functions? [duplicate]
I'm a bit confused with the use of methods like __iter__() and __next__() (I suppose they are called dunders).
I was trying to understand iterators and iterables and wrote this code:
x = (1, 2, 3, 4, ...
3
votes
1answer
109 views
How can I check if an identifier is dunder or class-private (i.e. will be mangled)?
I'm writing a project that gives advice about variable names, and I want it to tell if a name matches any of the reserved classes of identifiers. The first one ("private") is pretty ...
2
votes
1answer
103 views
overloading arbitrary operator in python
Is it possible to overload arbitrary operators in Python? Or is one restricted to the list of operators which have associated magic methods as listed here: https://www.python-course.eu/...
4
votes
1answer
39 views
Iterate over a type without instantiating it
Problem
I want to be able to iterate over a type without instantiating it, similar to an enum.
class Foo:
"""Class I want to iterate over without instantiating."""
...
4
votes
2answers
349 views
__dict__ Attribute of Ultimate Base Class, object in Python
Following piece of code lists the attributes of a class named 'A' in a sorted order:-
>>> class A():
def __init__(self, i):
self.at = i
>>> sorted(vars(A))
['...
1
vote
1answer
22 views
Is using magic methods quicker than using operator in python?
I want to ask that is using magic methods( like int.__add__()) is quicker than using operators (like +) ?
will it make a difference even by a bit?
thanks.
0
votes
0answers
32 views
PHP get magic method not working properly
This is what I have currently:
class Cart
{
protected $user;
public function __construct(User $user = null)
{
$this->user = $user ?? auth()->user();
}
public function ...
0
votes
0answers
51 views
Why Microsoft python analysis engine doesn't recognize some dunders(magic methods)on vs code?Is there an alternative extension to use instead?
I wrote some magic methods, but Microsoft python extension didn't recognize them and there was no auto-complete for them. This methods are __iter__ and __getattr__.
I tried Jedi engine but it didn't ...
0
votes
1answer
28 views
Merging / grouping class instances
So I have this task to practice Polymorphism and usage of abstract classes:
Create a class called Person. Upon initialization it will receive a
name (str) and a surname (str). Create another ...
2
votes
1answer
52 views
Why does int.__eq__ seem to be not implemented in python2 [duplicate]
I've got a head scratchier and it seems I'm not the only one, but is there really no solution? I find that hard to believe!
So the question is why can't I call int.__eq__ with 2 operators or i....
0
votes
2answers
357 views
autosummary generated documentation missing all dunder methods except for `__init__`
I am using Sphinx's autosummary to automatically generate individual rst files for each member of my module. The documentation is created as expected, except that the generated rst files are missing ...
2
votes
1answer
75 views
Python: How to use __add__ special method to add instances of the same class that return another instance of that class
Writing a program for a card game is what motivated the question. Currently, the way I defined the __add__ special method, I can in fact do something like this:
deck_one = Deck()
deck_two = Deck()
...
2
votes
2answers
55 views
Is it possible to transform default class dunder methods into class methods?
To give you some context, yesterday I came across this post. I found the problem quite interesting, so I tried to find a solution that would keep the syntax as close as possible to what was asked. ...
0
votes
1answer
25 views
Python Data Model : Overriding special method “contains”
So I am trying to understand python better with the book "Fluent Python". In python data model the author describes how special methods can be defined for classes.
class FrenchDeck:
ranks = [...
-1
votes
1answer
18 views
Define value of class when assigned to variable in PHP
In PHP I can use \ArrayAccess to create an object such that it can be assigned as variable (an array) but also execute some other stuff while doing it, is it possible to do the same with a single ...
0
votes
0answers
23 views
calling dunder methods using 'with' [duplicate]
A while back I came across this code on Stack Overflow for locking a directory:
import os
import fcntl
import time
class LockDirectory(object):
def __init__(self, directory):
assert os....
4
votes
1answer
44 views
How do I add a rabbit to a number in Python?
I can add a number to a Rabbit class, but not the other way around:
class Rabbit:
def __init__(self, age):
self.age = age
def __add__(self, rabbit):
if isinstance(rabbit, ...
0
votes
0answers
31 views
Can an instance return values other than a __repr__ string representation?
Here's an example of the phenomenon I'm looking at:
class Person:
def __init__(self, name, other):
self.name = name
self.other = other
class Name():
def __init__(self, ...
0
votes
2answers
146 views
Python how to print full stack, including magic methods (dunder methods) used?
I am trying to debug a Python built-in class. My debugging has brought me into the realm of magic methods (aka dunder methods).
I am trying to figure out which dunder methods are called, if any. ...
1
vote
2answers
76 views
Using namedtuple in class
I am practicing on a piece of code from the O'Reily's book Fluent Python.
The piece of code is as followed:
import collections
Card= collections.namedtuple('Card',['rank','suit']);
class ...
3
votes
2answers
149 views
Should I use python magic methods directly?
I heard from one guy that you should not use magic methods directly. and I think in some use cases I would have to use magic methods directly. So I am asking from the Senior Experienced Python ...
1
vote
0answers
16 views
Way to trace magic methods that were invoked during code execution
Is there a way to trace Python magic methods that were invoked during code execution?
For example, if I have this program:
class a:
def __init__(self):
self.x = 0
## Some wonder function ...
3
votes
2answers
186 views
How to make 2 different __mul__ methods
I built a matrices calculator and
I want to make one mul method for multiplication by scalar And another one for multiplication by other matrix. I have an if- else block but I prefer it to be in two ...