Reputation: 12452
zoo.py
from main import animal
def getAnimal(animal)
1) if animal == animal.tiger:
or
2) if animal == "animal"
and
main.py
import Zoo
Class animal
tiger = "tiger"
bear = "bear"
1) get = Zoo.getAnimal(animal.tiger)
or
2) get = Zoo.getAnimal("tiger"):
The above is extremely basic example but what is the "best" convention of performing the above code?
I was told it is better to do it via 1) approach because "strange things happen due to how python uses pointers."
Whats happening in terms of at memory level when the above codes are executed?
If I remember correctly, each memory addr gets ascii value of char for the conseq allocated memory address for strings?
Is it the same when string is now being referenced as an object that of animal.tiger?
Or are there no differences at all?
Upvotes: 1
Views: 151
Reputation: 6165
If the compiler doesn't optimize the code (i.e. it's more complex than your example) #2 will allocate an anonymous string with another pointer.
But since ==
do string compare it will work even if it is two different strings (in memory).
In your example the compiler will most likely optimize the code to be the same:
>>> class animal:
... tiger = "tiger"
... bear = "bear"
...
>>> animal.tiger
'tiger'
>>> id(animal.tiger)
140052399801616
>>> id('tiger')
140052399801616
>>>
EDIT: Added example of user input where string memory location differ:
>>> id(animal.tiger)
140052399801616
>>> a=raw_input()
tiger
>>> id(a)
140052399801664
>>> a==animal.tiger
True
>>> a is animal.tiger
False
(use is
to compare objects in memory as above)
Upvotes: 2