Помогите разобраться с кодом.
class Number:
def __init__(self, val):
self.val = val
def __iadd__(self, other):
self.val += other
return self
Не пойму в чем механика
class Number:
def __init__(self, val):
self.val = val
def __iadd__(self, other):
self.val += other
return self
DenLadon
Почему возвращается self а не self.val?
Не пойму в чем механика
a="asd" b=a a+="123" print(a) print(b) >>> asd123 >>> asd
class Number1: def __init__(self, val): self.val = val def __iadd__(self, other): self.val += other return self
>>> a = Number1(5) >>> a += 1 >>> a 6 >>> a.val Traceback (most recent call last): File "<pyshell#55>", line 1, in <module> a.val AttributeError: 'int' object has no attribute 'val'
class Number2: def __init__(self, val): self.val = val def __iadd__(self, other): self.val += other return self
b = Number2(5) >>> b += 1 >>> b <__main__.Number object at 0x000001A6B4E875F8> >>> b.val 6
These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self).
DenLadon
Получается следующее:>>> a = Number1(5) >>> a += 1 >>> a 6 >>> a.val Traceback (most recent call last): File "<pyshell#55>", line 1, in <module> a.val AttributeError: 'int' object has no attribute 'val'
>>> class Number1: ... def __init__(self, val): ... self.val = val ... def __iadd__(self, other): ... self.val += other ... return self ... >>> a = Number1(5) >>> a += 1 >>> a <__main__.Number1 object at 0xb739a50c> >>> a.val 6 >>>
>>> class Number1: ... def __init__(self, val): ... self.val = val ... def __iadd__(self, other): ... self.val += other ... return self ... def __repr__(self): ... return str(self.val) ... >>> a = Number1(5) >>> a += 1 >>> a 6 >>> a.val 6 >>>
DenLadonТы просто результаты не того кода смотришь. Если возвращаешь self.val, то там лежит обычное число, у которого нет атрибута val. Если возвращаешь self, то там лежит этот объект, у которого есть атрибут val.
Не понятно почему а, изначально определена как экземпляр класса становиться обычным числом.
py.user.nextЭто утверждение очевидно неверно.
В питоне разницы нет, что там возвращать
class Number1: def __init__(self, val): self.val = val def __iadd__(self, other): self.val += other return self a = Number1(1) a += 1 print(a) >>> <__main__.Number1 object at 0x0000002404762208> class Number1: def __init__(self, val): self.val = val def __iadd__(self, other): self.val += other return self.val a = Number1(1) a += 1 print(a) >>> 2
doza_andДля внутренних нужд используется возвращаемое значение. Сама операция нужна, чтобы поменять объект, и никак не должна его терять. Но бывают случаи, когда объект проще создать заново с нужными изменениями, чем менять существующий.
Это утверждение очевидно неверно.
#include <iostream>
using namespace std;
class A {
int n;
public:
A() : n(0) {}
float operator +=(int v) { n += v * 10; return 2.7; }
void print() { cout << n << endl; }
};
int main()
{
A n;
n.print();
cout << ((n += 2) + (n += 3)) << endl;
n.print();
return 0;
}
[guest@localhost cpp]$ .iso++ t.cpp -o t; ./t
0
5.4
50
[guest@localhost cpp]$