python调用类的方法使用不同的方法 [英] python calling methods of class using different ways
问题描述
我有一些类:
class RSA:
/ pre>
CONST_MOD = 2
def __init __ ):
printcreated
def fast_powering(self,number,power,mod):
printpowering
我想实例化它并调用方法fast_powering:
def main():
obj = RSA()#这里创建类的瞬时
val = obj.fast_powering(10,2,obj.CONST_MOD)#并且调用对象的方法
print val
而且工作正常!
但我发现我可以做一个有点不同的方式,如:
def main():
obj = RSA #do我们创建一个链接到类,而不创建对象,或什么?
val = obj()。fast_powering(10,2,obj()。CONST_MOD)#这里我们做一些类似
#调用C ++中静态方法的类,无需类实例化,
# 要么 ?对我有用[0]丢个板砖[0]引用|举报|编辑删除管理c $ b给我的惊喜它也工作了!
这里发生了什么?哪个wayn更优先?解决方案
<在您的示例中,您正在:
obj = RSA
只是将
obj
绑定到RSA
,这是您的实例中的类RSA
。然后你正在做:obj()。fast_powering(...)
/ pre>
这相当于创建
RSA
的实例并调用fast_powering
就可以了。注意,这样,每次调用都会得到一个RSA
的新实例,这可能不是你想要的。你也会注意到,在上面引用的行中已经调用了__ init __
方法。还请考虑:>>> class RSA:
... def __init __(self):
... print(foo)
...
>>> obj = RSA
>>>>> obj()is obj()
foo
foo
False
这里我们看到语句
obj()是obj()
实际上创建两个对象,当然不是相同的。这与您的第一个示例相反,如下所示:>> class RSA:
... def __init __(self):
... print(foo)
...
>>> obj = RSA()
foo
>>>> obj is obj
True
I have some class:
class RSA: CONST_MOD=2 def __init__(self): print "created" def fast_powering(self,number,power,mod): print "powering"
I want to instantiate it and call method fast_powering:
def main(): obj=RSA() # here instant of class is created val=obj.fast_powering(10,2,obj.CONST_MOD) # and we call method of object print val
And it works fine!
But I found that I can do it a little bit different way too, like:
def main(): obj=RSA #do we create a link to the class without creating of object , or what? val=obj().fast_powering(10,2,obj().CONST_MOD) # and here we do something like # calling of static method of class in C++ without class instantiation, # or ? print val
Sorry, I think a little bit in C++ way, but anyway to my great astonishment it works too!
What's actually happening here? Which wayn is more preffered? It's some misterious for me.Thanks in advance for any replies!
解决方案In your example, you're doing:
obj = RSA
which is just binding the name
obj
to whatever was bound toRSA
, which is the classRSA
in your instance. Then you're doing:obj().fast_powering(…)
Which is equivalent to creating an instance of
RSA
and calling the methodfast_powering
on it. Note that this way, you'll get a new instance ofRSA
on each call, which is probably not what you want. You'll also have noticed, that the__init__
method has been called in the line cited above. Also consider:>>> class RSA: ... def __init__(self): ... print("foo") ... >>> obj = RSA >>> obj() is obj() foo foo False
Here we see that the statement
obj() is obj()
in fact creates two objects, which are of course not identical. This is opposed to your first example, as demonstrated using:>>> class RSA: ... def __init__(self): ... print("foo") ... >>> obj = RSA() foo >>> obj is obj True
这篇关于python调用类的方法使用不同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!