需要了解的:
__ slots __:属于魔术变量,即:系统实现某些特定功能的变量
__ slots __:
1.限定类实例能添加的属性
2.对当前类起作用,对继承的子类是不起作用的
实操:
# coding:utf8
import traceback
from types import MethodType
class CustomClass(object):
pass
# class CustomClass(object):
# __slots__ = ['name', 'set_name']
def set_name(self, name):
self.name = name
custom_class = CustomClass()
custom_class.name = "Thanlon" # 动态添加属性
custom_class.set_name = MethodType(set_name, custom_class) # 添加set_name方法作用在cusClass类中
custom_class.set_name("Tangtang")
print(custom_class.name)
try:
custom_class.sex = '女'
print(custom_class.sex)
except AttributeError:
traceback.print_exc()
class ExtMyClass(CustomClass):
pass
ext_class = ExtMyClass()
ext_class.sex = '男'
print(ext_class.sex)