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:
which is just binding the name
objto whatever was bound toRSA, which is the classRSAin your instance. Then you’re doing:Which is equivalent to creating an instance of
RSAand calling the methodfast_poweringon it. Note that this way, you’ll get a new instance ofRSAon 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: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: