from vs import | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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??

1st Aug 2018, 7:33 AM
Ultra Yam ZGH
Ultra Yam ZGH - avatar
5 Answers
+ 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.
1st Aug 2018, 7:56 AM
apex137
apex137 - avatar
+ 1
Thnx @Jericho Arcealo so if I already have a replace function in both cases it overrides the imported replace function.. is that right??
1st Aug 2018, 11:24 AM
Ultra Yam ZGH
Ultra Yam ZGH - avatar
+ 1
Correct @Ultra Yam ZGH
2nd Aug 2018, 1:37 AM
apex137
apex137 - avatar
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
1st Aug 2018, 10:08 AM
Sousou
Sousou - avatar
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??
1st Aug 2018, 11:23 AM
Ultra Yam ZGH
Ultra Yam ZGH - avatar