在课堂上使用'__mul__' [英] Using '__mul__' within a class
问题描述
你好
我是Python的新手,想知道为什么'/'
中的'Square'方法以下代码没有'''工作。它不会失败,只是不做任何事情(至少,不是我想要的!)。平方后为什么'a''等于2
?
TIA。
类FibonacciMatrix:
def __init __(个体经营):
self.a = 1
self.b = 1
self.c = 0
def __mul __(self,other):
result = FibonacciMatrix()
result.a = self.a * other。 a + self.b * other.b
result.b = self.a * other.b + self.b * other.c
result.c = self。 b * other.b + self.c * other.c
返回结果
def Square(个体经营):
self * =自我
A = FibonacciMatrix()
A.Square()
打印Aa #prints''1''
A = FibonacciMatrix()
B = A * A
打印Ba #prints''2' '
------------------------------
>
推荐答案
出于同样的原因,
def f(z):
z * = z
c = 1
f(c)
打印c
打印1.
杰夫
-----开始PGP签名 - ---
版本:GnuPG v1.4.1(GNU / Linux)
iD8DBQFDNXm7Jd01MZaTXX0RAguqAJ9u9Txaz8AOJaBn4t3v1e + ExsQ0DACgiv2l
urtGBbqtiSXWM4SKoBcP77E =
= mTpx
-----结束PGP签名-----
For the same reason that
def f(z):
z *= z
c = 1
f(c)
print c
prints 1.
Jeff
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)
iD8DBQFDNXm7Jd01MZaTXX0RAguqAJ9u9Txaz8AOJaBn4t3v1e +ExsQ0DACgiv2l
urtGBbqtiSXWM4SKoBcP77E=
=mTpx
-----END PGP SIGNATURE-----
Gerard Flanagan写道:
Gerard Flanagan wrote:
def Square(self):
self * = self
你可能意味着
返回自我*自我
A = FibonacciMatrix()
A.Square()
def Square( self ):
self *= self
You probably mean
return self * self
A = FibonacciMatrix()
A.Square()
制作此
A = A.Square()
Make this
A = A.Square()
" Gerard Flanagan" < GR ******** @ yahoo.co.uk>在消息中写道
news:11 ********************** @ g49g2000cwa.googlegr oups.com ...
"Gerard Flanagan" <gr********@yahoo.co.uk> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
def __mul __(自我,其他):
def Square(个体经营):
自我* =自我
def __mul__( self, other ):
def Square( self ):
self *= self
其他原因引用,我认为''op =''映射到与''op''不同的特殊方法。 __imul__?或者其他的东西?做检查。
tjr
Among the other reasons cited, I believe that ''op='' maps to a different
special method than ''op''. __imul__? or something? do check.
tjr
这篇关于在课堂上使用'__mul__'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!