For a self-project, I wanted to do something like:
class Species(object): # immutable.
def __init__(self, id):
# ... (using id to obtain height and other data from file)
def height(self):
# ...
class Animal(object): # mutable.
def __init__(self, nickname, species_id):
self.nickname = nickname
self.species = Species(id)
def height(self):
return self.species.height()
As you can see, I don't really need more than one instance of Species(id) per id, but I'd be creating one every time I'm creating an Animal object with that id, and I'd probably need multiple calls of, say, Animal(somename, 3)
.
To solve that, what I'm trying to do is to make a class so that for 2 instances of it, let's say a and b, the following is always true:
(a == b) == (a is b)
This is something that Python does with string literals and is called internship. Example:
a = "hello"
b = "hello"
print(a is b)
that print will yield true (as long as the string is short enough if we're using the python shell directly).
I can only guess how CPython does this (it probably involves some C magic) so I'm doing my own version of it. So far I've got:
class MyClass(object):
myHash = {} # This replicates the intern pool.
def __new__(cls, n): # The default new method returns a new instance
if n in MyClass.myHash:
return MyClass.myHash[n]
self = super(MyClass, cls).__new__(cls)
self.__init(n)
MyClass.myHash[n] = self
return self
# as pointed out on an answer, it's better to avoid initializating the instance
# with __init__, as that one's called even when returning an old instance.
def __init(self, n):
self.n = n
a = MyClass(2)
b = MyClass(2)
print a is b # <<< True
My questions are:
a) Is my problem even worth solving? Since my intended Species object should be quite light weight and the max amount of times Animal can be called, rather limited (imagine a Pokemon game: no more than 1000 instances, tops)
b) If it is, is this a valid approach to solve my problem?
c) If it's not valid, could you please elaborate on a simpler / cleaner / more Pythonic way to solve this?