对于自我项目,我想做类似的事情:
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()
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我真的不需要每个id有一个以上的Species(id)实例,但每次我创建一个具有该id的Animal对象时我都会创建一个,并且我可能需要多个比方说的Animal(somename, 3).
为了解决这个问题,我要做的是创建一个类,以便对于它的2个实例,让我们说a和b,以下总是如此:
(a == b) == (a is b)
Run Code Online (Sandbox Code Playgroud)
这是Python用字符串文字做的事情,称为实习.例:
a = "hello"
b = "hello"
print(a is b)
Run Code Online (Sandbox Code Playgroud)
该print将产生true(只要字符串足够短,如果我们直接使用python shell).
我只能猜测CPython是如何做到的(它可能涉及一些C魔法)所以我正在做我自己的版本.到目前为止我有:
class MyClass(object):
myHash = {} # This replicates the intern pool. …Run Code Online (Sandbox Code Playgroud)