+ 1
from vs import
So...this is the question..considering working in python 2.7. if I already have a replace () method in my program & also do these:- 1. import string s='sample' s=string.replace('s','m','a') 2. from string import replace s='sample' s=string.replace('s','m','a') P.S:I haven't checked them out... but if you already have a replace () method in my program what will happen??
5 Réponses
+ 1
'import' simply imports a whole class, with all properties and methods inside of it.
' from ___ import ___' imports only the specified part of a class. This is useful when you only need to get a small part from a large class.
In your case, when you import the string library and use replace, there would be no issues since you'll have to call the class name before the function anyway. But importing only the replace method means that when you call replace, the interpreter would automatically default to calling that method, so technically you can still call string.replace() with replace() only if you import only the method.
But if there is already a defined function in the script apart from the imported method with the same name, the interpreter would pick the one in the script instead, since you overridden its imported declaration.
+ 1
Thnx @Jericho Arcealo so if I already have a replace function in both cases it overrides the imported replace function.. is that right??
+ 1
Correct @Ultra Yam ZGH
0
example:
1)
import random
a=random.randint(0, 100)
==
2)
from random import randint
a=randint(0, 100)
-->> The second method is The shortest
0
@ Sou Sou that's correct but my question was what happens if I already have a randint() function in my program along with the randint() from Math class??