控制类只被调用一次::
方法1:
class A:
num = 1
def __new__(cls, *args, **kwargs):
if cls.num==1:
cls.num+=1
return super().__new__(cls)
print("已经被调用一次了")
def __init__(self):
pass
方法2:
class C:
num = 1
def __init__(self):
if C.num != 1:
raise Exception
C.num += 1
控制类方法只被调用一次:
方法1:
class MyExceptions(Exception):
pass
class B:
def __init__(self):
pass
def test00(self):
try:
self.value # 利用实例化后实例属性,参数的结果是否会报错
raise MyExceptions('已经调用一次了')
except AttributeError:
self.value = 0
print(self.value)
方法2:
class C:
num = 1 # 利用修改类属性
def test00(self):
if C.num != 1:
raise Exception
C.num += 1