__slots__方法是为了限制在该类中(不是实例)不可定义其他属性请看代码:(看完后运行)
class Test:
__slots__ = ('name', 'age')
def __init__(self, ch):
self.ch = ch
try:
test = Test(123)
print(test.ch)
except AttributeError as error:
def __init__(self, age):
self.age = age
print('%s:报错信息,说明try的函数体执行错误了' % error)
print('把初始化方法的参数ch换成age')
finally:
print(test.age)
print(""" 说明__slots__仅提供了对实例对象的两个属性,分别是name和age,其他的属性会报错,
在Test类中定义其他属性也是不行的,说白了__slots__方法只能定义他指向的属性,
且不能在类中定义,只能在实例化对象中定义""")
Sign in to make a reply
你眼训可以走先JIA
__slots__方法是为了限制在该类中(不是实例)不可定义其他属性请看代码:(看完后运行)
class Test:
__slots__ = ('name', 'age')
def __init__(self, ch):
self.ch = ch
try:
test = Test(123)
print(test.ch)
except AttributeError as error:
class Test:
__slots__ = ('name', 'age')
def __init__(self, age):
self.age = age
test = Test(123)
print('%s:报错信息,说明try的函数体执行错误了' % error)
print('把初始化方法的参数ch换成age')
finally:
print(test.age)
print(""" 说明__slots__仅提供了对实例对象的两个属性,分别是name和age,其他的属性会报错,
在Test类中定义其他属性也是不行的,说白了__slots__方法只能定义他指向的属性,
且不能在类中定义,只能在实例化对象中定义""")