Questions tagged [magic-methods]
Magic methods are implicitly invoked by a programming language when some event or language construct is used.
581
questions
0
votes
0
answers
20
views
Unable to get repr for class models
I have django project and I create class SaleProduct in models.py in items package
now in find_items.py, after import class SaleProduct, couldn't create an instance of class SaleProduct --> in ...
6
votes
2
answers
76
views
How can I override a special method defined in a metaclass with a custom classmethod?
As an example, consider the following:
class FooMeta(type):
def __len__(cls):
return 9000
class GoodBar(metaclass=FooMeta):
def __len__(self):
return 9001
class BadBar(...
0
votes
0
answers
20
views
Only if I'm not using __iadd__, I get TypeError: can only concatenate list (not "str") to list [duplicate]
Why does this work ...
>>> a = [0, 1, 2]
>>> a += "x" * 3
>>> a
[0, 1, 2, 'x', 'x', 'x']
... but this doesn't?
>>> [0, 1, 2] + "x" * 3
...
0
votes
1
answer
11
views
How to avoid RuntimeError while call __dict__ on module?
it is appearing in some big modules like matplotlib. For example expression :
import importlib
obj = importlib.import_module('matplotlib')
obj_entries = obj.__dict__
Between runs len of obj_entries ...
0
votes
2
answers
45
views
Python: use special methods on a class (not necessarily its instances)
(Edited to frame it as a question as requested by the guidelines)
I am implementing this class to manage a library of prime numbers, the instances are supposed to work as a range object, but on primes ...
2
votes
1
answer
28
views
Generic lazy initializer class and magic methods
I want to create a class that lazily initializes objects in the background when they are first used, but that behaves exactly like the initialized objects. It should be thread-safe. For example:
In[1]:...
0
votes
1
answer
20
views
Add (+) a custom class object to a numeric object in Python
I know how to use magic methods to define mathematical operators in a custom class.
class CustomDataClass:
def __init__(self, data):
self.data = data
def __str__(self):
...
4
votes
3
answers
72
views
When will the Python special method (i.e. magic method) __len__ be called?
I'm trying to make a Link-List Node class for a Link-List, as shown in the code:
class LNode:
def __init__(self, data=None, pnext=None):
self.data = data
self.pnext = pnext
...
0
votes
1
answer
56
views
How to make Python class constructor return an already existing object (pointing to the same object)?
I'm writing a class called Position, something like Python's Small Integer Constant Pool:
class Position:
"""Takes 2 args: x, and y. If coordinate are equal, make them pointing to ...
0
votes
2
answers
24
views
Compare two String by length only in a special class using __eq__?
I'm trying to create a Class to compare two String only by length (using the Magic method). Here is my code:
class CustomString:
def __init__(self,string):
self.string=string
...
0
votes
1
answer
21
views
Python - refering/redirecting to operator magic method of member attribute
I've a question regarding overriding operator magic methods. I'm trying to provide the methods/attributes of value to the object a which holds that attribute. I would like to do so, because I have an ...
1
vote
1
answer
41
views
Is there some magic method that is invoked when a constant of a class doesn't exist in PHP?
I would like to know if there is, in PHP, some magic method that is invoked when a constant doesn't exist. I know __callStatic() is invoked when a static method doesn't exist, but what about constant, ...
1
vote
0
answers
26
views
How to prevent the default inplace add `__iadd__` calling the reflected add `__radd__` of my class in Python?
I have a class where I have defined the reflected add (__radd__) special method:
class Addable:
def __init__(self, other=0):
if isinstance(other, Addable):
self.id = other.id
...
0
votes
2
answers
129
views
Do special functions get called every time I create an object?
Just like the __init__() method, do the other special functions get called automatically when I create an object?
Check out this simple class for example:
class Point:
def __init__(self, x = 0, y =...
-1
votes
1
answer
77
views
Do Python 2 and 3 share the same set of magic methods?
Do Python 2 and 3 share all the same magic methods (with their names being exactly the same)?
If not, does anyone know of a handy comprehensive list of all the magic methods in Python 3?
0
votes
2
answers
58
views
What are the other uses of __new__ method in python?
Here I have defined immutable class str.
In new method I am changing the values of instances such as "hello" to uppercase. Why should we do it using new when we can define upper in init ?
...
0
votes
1
answer
39
views
Query attribute name together with its class
The name of an attribute can be asked with __name__. However, I also want to inquire about the class name:
class Test:
__slots__ = ['a', 'b']
print(Test.a.__name__) # → 'a' but wanted 'Test.a' or ...
0
votes
1
answer
41
views
Is there any magic method for reflected augmented assignment?
I have two user-defined classes, a and b. For such an augmented addition assignment between them:
a += b
Where a returns NotImplemented when it encounters b, is it expected that Python will look for ...
0
votes
0
answers
77
views
Time complexity of __getitem__ in python
hope you are all doing fine.
I just want to know what is runtime complexity for this case? and is the run time complexity for all cases such as dictionary, list, tuple and etc... to extract of the end ...
0
votes
0
answers
45
views
How to create a class decorating another class using python
My goal is to implement a classic Decorator pattern (not functional @decorator, provided by python from the box). But I don't want to implement every method and attribute in decorator class. I want to ...
0
votes
1
answer
45
views
Python Multiprocessing manager prunes some methods
I've found that Manager rarely works in practice with most of the custom objects as it removes some class members. See an example:
from multiprocessing import Manager
from scipy.interpolate import ...
1
vote
1
answer
48
views
Can magic methods return different result type?
Can a magic method like def __sub__() which operates on a type return a different result type?
For example in below class User, the -1 operator returns a string. The requirement is if there is ...
0
votes
0
answers
21
views
How to overcome Python parser/interpreter translation of `a > b > c` to `a > b and b > c` in overrided operators?
I've read most of the PEP 207 and other sources, and it confirms that the Python interpreter desugars a > b > c to a > b and b > c.
However, this happens even if the magic method for this ...
30
votes
7
answers
3k
views
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 ...
0
votes
0
answers
24
views
How to change behaviour of object on MongoDB saving?
I have class and with magic methods I can change behaviour on calling / iterating and so on. But I want to change behaviour on saving in MongoDB.
For example I have object User. And when I call db....
1
vote
1
answer
147
views
Sequelize magic method not found using Express and Node.JS
I'm coding an application using Sequelize, Express and Node.JS; after set a OneToMany relationship between User and Product, just like this:
app.js:
Product.belongsTo(User, { constraints: true, ...
0
votes
0
answers
46
views
How to run a ipynb notebook function from inside notebook with arguments
I have a jupyter notebook function
def add_args(a: int, b: int) -> int:
return a + b
a = sys.argv[1] # 0 is file name
b = sys.argv[2]
print("sum of {} and {} is {}".format(a, b, ...
3
votes
1
answer
91
views
Why doesn't __qualname__ work the same way in @classmethod than in metaclass
I have implemented a minimalistic enum by writing
class SymbolClass(type):
def __repr__(cls): return cls.__qualname__
class Symbol(metaclass=SymbolClass): pass
class Animal:
class Dog(Symbol):...
1
vote
2
answers
70
views
__getattr__ for class atributes?
For a class Foo,
class Foo:
...
is there a way to call a specific method whenever Foo.XXX (an arbitrary class attribute XXX, such as bar, bar2, etc.) is being resolved, but NOT whenever Foo().XXX ...
-1
votes
1
answer
92
views
Python wrapper get wrapped object
I do have a wrapperclass for a specific object giving it some extra methods.
However this object (wrapped or not) is often passed as an argument. In this case I want to past the original (wrapped) ...
0
votes
1
answer
53
views
How to await inside a dunder method?
I want to make an async database query and insert it inside cls.__setitem__ but of course, I can't use await inside a sync function. how can I tackle this problem?
4
votes
2
answers
102
views
Why is `x[i]` not equivalent to `x.__getitem__(x)`?
From the documentation:
x[i] is roughly equivalent to type(x).__getitem__(x, i).
What is the benefit of the above rather than having a seemingly simpler x.__getitem__(i)?
EDIT: Why is Python ...
3
votes
2
answers
436
views
How to use dunder methods for object comparison [closed]
Comparing two objects using dunder methods
I was trying to compare two 'Time objects', but I got this error:
'TypeError: '<' not supported between instances of 'Time' and 'Time'
This is what I ...
1
vote
2
answers
66
views
Refactoring a Python class to take a dynamic parameter without changing calling pattern dramatically
I have a Python class in a base_params.py module within an existing codebase, which looks like this:
import datetime
class BaseParams:
TIMESTAMP = datetime.datetime.now()
PATH1 = f'/foo1/bar/{...
1
vote
1
answer
45
views
Method with same name in Derived class wrongly called in Parent class while using inheritance in Python
I have the following code
class Parent(bytes):
def __init__(self, validate=True):
super().__init__()
if validate:
self.validate()
def validate(self):
print(...
5
votes
2
answers
86
views
Equality Comparison with NumPy Instance Invokes `__bool__`
I have defined a class where its __ge__ method returns an instance of itself, and whose __bool__ method is not allowed to be invoked (similar to a Pandas Series).
Why is X.__bool__ invoked during np....
0
votes
2
answers
123
views
calling __isset() magic method from empty() function, the magic method returns true but actually it should return false
class Base
{
private $firstName;
private $lastName;
function setName($firstName, $lastName){
$this->firstName = $firstName;
$this->lastName = $lastName;
}
function __isset($...
0
votes
1
answer
71
views
What is the difference between using magic method of a class with following syntaxes in Python: method(member) and member.__method__()?
I created a class and specified the attributes of the member with the following code:
Mexico_66 = Product('Mexico 66 VIN', 99.90, 4)
In the class, I have defined the following magic method:
def ...
0
votes
0
answers
32
views
Numpy-like methods for own classes
I have spent a day on chasing a bug on the following kind: I have a matrix M, which I used a numpy.ndarray for until now, on which I somewhere in the programm call numpy.flip(M). I have decided that ...
0
votes
1
answer
277
views
How to know which method is called in Laravel controller
When a request comes to Laravel controller through application router, how can we determine which method is called inside that controller? I mean inside constructor or magic methods of the controller. ...
0
votes
0
answers
110
views
Python3: Do subclasses of an abstract class inherit its magic methods?
Here's the tea: I'm writing a small Monopoly game using python. I've made this little class family to represent the bills. There's a base abstract class called Bill which inherits from the abc.ABC ...
0
votes
1
answer
74
views
Can a class instance return tuple without using attribute?
I've got a small problem which in itself isn't a big deal but is bugging me none the less. Consider the code below.
import pygame
class vector:
def __init__(s, x, y):
s.x = int(x)
...
-1
votes
1
answer
162
views
why can a class call a magic method from another class?
class Example:
def __init__(self):
print("init called")
def some_method(self):
print("some method called")
Why can a class call the constructor of another ...
0
votes
2
answers
311
views
Should I not use built-in tuple specific functions?
When I look up the methods for the built-in collection type tuple online, it says that tuples have only two methods:count() and index(). However, whenever I try to look up pydoc for tuples:
python -m ...
0
votes
1
answer
81
views
Python - detect asterisk (*) during function call
I need to detect that function is called with asterisk (*) when unpacking
Problem:
I have a special class that registers __getitem__ keys.
these slicings will pass the obvious keys to __getitem__:
...
1
vote
1
answer
292
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
3
answers
43
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....
4
votes
1
answer
108
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
1
answer
75
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
0
answers
20
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'...