在python中,有没有办法在定义对象后防止添加新的类变量?
例如:
class foo:
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
bar = foo()
try:
bar.d = 4
except Exception, e:
print "I want this to always print"
或者,有没有办法计算对象中变量的数量?
class foo:
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
def count(self):
...
bar = foo()
if bar.count() == 3:
print "I want this to always print"
我想到这样做的唯一方法是使用字典或列表:
class foo:
def __int__(self):
self.dict = {'foo':1, 'bar':2}
self.len = 2
def chk():
return self.len == len(self.list)
然而,这样做对 python 来说感觉相当麻烦。(obj.dict['foo'])。如果可能的话,我更喜欢 obj.foo 。
我想拥有它,这样当我打算更改现有变量时,我就不会意外地声明一个变量。
f = foo()
f.somename = 3
...
f.simename = 4 #this is a typo
if f.somename == 3:
solve_everything()