前面的讲解可以看出 ,方法和属性都可以为所欲为的添加,为了限制你的能力必须给你戴上紧箍咒。
这个紧箍咒是什么呢 slots, 它的作用就是给你个范围,你只能在这个范围蹦跶,超出了就枪毙, 强调下只是针对实例。
注意下, 我说的只是实例,并没有说类,对子类也不起作用。
看以下代码
class Person():
__slots__ = ("age", "name")
def __init__(self,name,age):
self.age=age
self.name=name
def run(self):
print("runing%s"%self.name)
p1=Person("laowang",90)
p1.age=16
p1.num=14
p1.name="xinxi"
报错如下:
p1.num=14
AttributeError: 'Person' object has no attribute 'num'
我们添加方法试试 如下:
import types
p1.run=types.MethodType(run,p1)
p1.run()
报错如下:
p1.run=types.MethodType(run,p1)
AttributeError: 'Person' object has no attribute 'run'
添加类 属性是不报错的, 如下:
class Person():
__slots__ = ("age", "name")
def __init__(self,name,age):
self.age=age
self.name=name
def run(self):
print("runing%s"%self.name)
import types
p1=Person("laowang",90)
Person.sex="male"
print(p1.sex)