最后,我回答了我自己的问题,我认为它应该可以解决问题(但如果有更pythonic和更简单的方法..我很想知道):
包含类 P 的模块 p
class P(object):
instance = None
nb_instance = 0
def __init__(self, **params):
assert type(self).instance is None, "no more than one instance of P is possible"
self.params = params
type(self).instance = self
type(self).nb_instance +=1
def __deepcopy__(self,el):
assert 1==0, "no deep copy of P is possible"
def __copy__(self):
assert 1==0, "no shallow copy of P is possible"
另一个尝试从类 P 实例化新元素的模块
import p
class OtherCode(object):
def __init__(self):
self.a = 1
self.p = p.P(sigma=4.0,mu=1.0)
最后是要运行的主要代码
import p,otherCode
import copy
if __name__ == '__main__':
P1 = p.P(sigma=0.1,mu=1.0)
#o =otherCode.OtherCode()
try:
P2 = copy.deepcopy(P1)
except Exception as E:
print(E)
try:
P3 = copy.copy(P1)
except Exception as E:
print(E)
try:
otherCode.OtherCode()
except Exception as E:
print(E)
P5 = P1
print("P1 is P5 {}".format(P1 is P5))
The output:
no deep copy of P is possible
no shallow copy of P is possible
no more than one instance of P is possible
P1 is P5 True